JavaScript Fun Question: Extracting Domain Names from URLs

https://blog.csdn.net/esir82/article/details/53333056

Given a URL string, how to parse it and extract the domain name from it?

As follows:

[javascript]  view plain copy  
  1. domainName("http://github.com/carbonfive/raygun") == "github"   
  2. domainName("http://www.zombie-bites.com") == "zombie-bites"  
  3. domainName("https://www.cnet.com") == "cnet"  

As we all know, the first part of the URL is the protocol name, which can be of many kinds, such as http , https , and even more protocols will be added in the future, so if all the protocol names are matched, the scalability is too poor .

However, no matter what your protocol is, this paragraph is essential - "://" .

And often, this string is followed by the domain name, and we can do string interception.

The following code explains in detail:

[javascript]  view plain copy  
  1.           
  2. function domainName(url){  
  3.     var sign = "://";  
  4.     var pos = url.indexOf(sign);  
  5.     //if it starts with the protocol name  
  6.     //Such as: http://github.com/  
  7.     if(pos >= 0){  
  8.         pos += sign.length;  
  9.         //Intercept the part after the protocol name  
  10.         //github.com/  
  11.         url = url.slice(pos);  
  12.     }  
  13.     // split by decimal point  
  14.     var array = url.split(".");  
  15.     //If it starts with 3W, return to the second part  
  16.     //Such as: www.github.com  
  17.     if(array[0] === "www"){  
  18.         return array[1];  
  19.     }  
  20.     //If it doesn't start with 3W, return the first part  
  21.     //Such as: github.com/  
  22.     return array[0];  
  23. }  

This method only considers several general situations, and some situations, such as subdomains, are not considered.


 function domainName(url) {
        var sign = "://";
        var pos = url.indexOf(sign);
        //if it starts with a protocol name
        //for example: http://github.com/
        if (pos >= 0 ) {
            pos += sign.length;
            //Intercept the part after the protocol name//
            github.com /
            url = url.slice(pos);
        }
        //Split by decimal point
        var array = url.split("/") ;


        if (array.length <= 1) {
            alert("The url format is incorrect, please end with /+ suffix");
            return false;
        }
        if (array.length == 2) {
            if (array[1].trim ().length==0) {
                alert("The url format is incorrect, Add suffix ending with ");
                return false;
            }
        }
        return true;
    }



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325399976&siteId=291194637