How to get base domain from the URL in JavaScript

后端 未结 9 546
萌比男神i
萌比男神i 2020-12-06 02:52

I would like to extract the base domain from the url in javascript. For example for the list of urls listed below I need to get google.com (or googl

9条回答
  •  半阙折子戏
    2020-12-06 03:48

    You can try this method

    var url = 'https://www.petzlover.com/us/search?pet=1&breed=262';

    extractHostname(url,true); //petzlover.com

    extractHostname(url); //www.petzlover.com

    function extractHostname(url,tld) {
          let hostname;
    
          //find & remove protocol (http, ftp, etc.) and get hostname
          if (url.indexOf("://") > -1) {
              hostname = url.split('/')[2];
          }else {
              hostname = url.split('/')[0];
          }
    
          //find & remove port number
          hostname = hostname.split(':')[0];
    
          //find & remove "?"
          hostname = hostname.split('?')[0];
    
          if(tld){
            let hostnames = hostname.split('.');
            hostname = hostnames[hostnames.length-2] + '.' + hostnames[hostnames.length-1];
          }
    
          return hostname;
      }

    let url = 'https://www.petzlover.com/us/search?pet=1&breed=262';
    
    let longUrl = 'https://www.fr.petzlover.com/us/search?pet=1&breed=262';
    
    let topLevelDomain = extractHostname(url,true); //petzlover.com
    let subDomain = extractHostname(url); //www.petzlover.com
    let lengthySubDomain = extractHostname(longUrl); //www.fr.petzlover.com
    
    document.getElementById('top-level-domain').innerHTML = topLevelDomain;
    document.getElementById('sub-domain').innerHTML = subDomain;
    document.getElementById('lengthy-sub-domain').innerHTML = lengthySubDomain;
    
        function extractHostname(url,tld) {
              let hostname;
        
              //find & remove protocol (http, ftp, etc.) and get hostname
              if (url.indexOf("://") > -1) {
                  hostname = url.split('/')[2];
              }else {
                  hostname = url.split('/')[0];
              }
        
              //find & remove port number
              hostname = hostname.split(':')[0];
    
              //find & remove "?"
              hostname = hostname.split('?')[0];
        
              if(tld){
                let hostnames = hostname.split('.');
                hostname = hostnames[hostnames.length-2] + '.' + hostnames[hostnames.length-1];
              }
        
              return hostname;
          }
    span{
      font-weight:bold;
      font-size:16px;
    }
    Top Level Domain:
    Including sub Domain:
    Including lengthy sub Domain:

提交回复
热议问题