How to Extract Base URL From Subdomain in Javascript and Node.js Full Tutorial 2020

How to Extract Base URL From Subdomain in Javascript and Node.js Full Tutorial 2020

 

Live Demo

 

 

 

You can see the live demo of the app here

 

 

 

Get Started

 

 

In order to get started we need to install a node.js dependency called as psl which will actually extract the base url from the subdomain so kindly first of all initialize a node.js project

 

 

npm init -y

 

 

This will create the package.json file and then install psl dependency like this

 

npm i psl

 

 

Now we want to create a index.js file and copy paste the following code

 

 

 


const express = require('express')

const bodyparser = require('body-parser')

const psl = require('psl')

const app = express()

app.set('view engine','ejs')

app.use(bodyparser.urlencoded({extended:false}))
app.use(bodyparser.json())

const PORT = process.env.PORT || 4000

app.get('/',(req,res) => {
    res.render('extractbaseurl',{title:"Bulk Base URL Extractor From Subdomains"})
})

app.post('/getbaseurlwithhttp',(req,res) =>{
    console.log(req.body.domain)
    var baseUrl = req.body.domain.protocol + "//" + req.body.domain.host + "/" + req.body.domain.pathname.split('/')[1];

    res.json({
        baseurl:baseUrl
    })

})

app.post('/getbaseurlwithouthttp',(req,res) =>{

var parsed = psl.parse(req.body.domain);

console.log(parsed.domain)

res.json({

baseurl:parsed.domain

})


})


app.listen(PORT)

 

 

 

Now we just need to make a AJAX Request from the html file to this node.js post request to get the base url from the subdomain.

See also  How to Show and Hide Div on Mouse Click in jQuery Using Javascript Full Project For Beginners

Now create a views folder inside your root project and inside it you create extractbaseurl.ejs file and copy paste the following code

 

views/extractbaseurl.ejs

 

 

<!DOCTYPE html>
<html>
  <head>
    <title><%=title%></title>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>

  </head>
  <body>
    <div class="container">
      <h1 class="text-center">Bulk Base URL Extractor From Subdomains</h1>
      <form id="form">
        <div class="form-group">
          <label for="domain">Enter Domains URL: (One Per Line)</label>
          <textarea
            class="form-control"
            rows="10"
            cols="20"
            id="domains"
            placeholder="Domain names"
            required
          ></textarea>
        </div>
        <label class="radio-inline"
          ><input type="radio" value="with" name="format" checked />(with
          http,https and www)</label
        >
        <label class="radio-inline"
          ><input type="radio" value="without" name="format" />(without
          http,https and www)</label
        >
        <div class="form-group">
          <button id="button" class="btn btn-block btn-danger">
            Extract Base URL's
          </button>
        </div>
      </form>
      <div>
        <div class="form-group">
          <label for="output">Output:</label>
          <textarea
            class="form-control"
            name=""
            id="result"
            cols="30"
            rows="10"
            placeholder="Output"
          ></textarea>
        </div>
      </div>
      <div class="form-group">
        <button id="copy" onclick="copytoclipboard()" class="btn btn-primary btn-block">
          Copy to Clipboard
        </button>
      </div>
    </div>
  </body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/psl/1.8.0/psl.min.js"></script>
  <script>
    var domains, format;
    $("#form").submit(function (e) {
      e.preventDefault();

      $("#result").empty();

      $("#button").text("Extracting Base URL Please Wait");

      $("#button").prop("disabled", "true");

      format = $("input[name='format']:checked").val();

      console.log(format);

      domains = $("#domains").val().split("\n");

      console.log(domains);

      domains.forEach((domain) => {
        var domain;
        console.log(domain);

        if (format == "without") {
          domain = domain
            .replace(/^(?:https?:\/\/)?(?:www\.)?/i, "")
            .split("/")[0];
          $.ajax({
            method: "POST",
            url: "/getbaseurlwithouthttp",
            data: { domain: domain },
            success: function (data) {
              console.log(data.baseurl);

              $("#button").text("Extract Base URL's");

              document.getElementById("button").disabled = false;

              $("#result").append(`${data.baseurl}\n`);
            },
          });
        } else {
          var temp = document.createElement("a");
          temp.href = domain;
          $("#result").append(`${temp.origin}\n`);

          $("#button").text("Extract Base URL's");

          document.getElementById("button").disabled = false;
        }
      });
    });
  </script>
  <script>

    function copytoclipboard(){
        var $temp = $("#result");
  var brRegex = /<br\s*[\/]?>/gi;

  $temp.val($($temp).html().replace(brRegex, "\r\n")).select();
  document.execCommand("copy");
  
    Swal.fire(
      'Good job!',
      'Base URLs Successfully Copied',
      'success'
    )
    }
    
    </script>    
</html>

 

See also  How to Replace all Occurrences of a String in JavaScript Using Regex Expression Full Project For Beginners

 

 

Screenshots

 

 

 

 

 

DOWNLOAD SOURCE CODE

 

 

Leave a Reply