Given a URL string, how to parse it and extract the domain name from it?
As shown below:
domainName("http://github.com/carbonfive/raygun") == "github" domainName("http://www.zombie-bites.com") == "zombie-bites" domainName("https://www.cnet.com") == "cnet"
As we all know, the first part of the URL is the protocol name. This can be of many types, such as http, https, and even more protocols will be added in the future. Therefore, if all protocol names are matched, the scalability will be very poor.
However, no matter what kind of agreement you have, this paragraph is essential - "://".
And often, this string is followed by the domain name, and we can intercept the string.
The following code explains in detail:
function domainName(url){ var sign = "://"; var pos = url.indexOf(sign); //如果以协议名开头 //如:http://github.com/ if(pos >= 0){ pos += sign.length; //截取协议名以后的部分 //github.com/ url = url.slice(pos); } //以小数点作分割 var array = url.split("."); //如果是以3W开头,返回第二部分 //如:www.github.com if(array[0] === "www"){ return array[1]; } //如果不是以3W开头,则返回第一部分 //如:github.com/ return array[0]; }
This method only considers several general situations. Some situations, such as subdomain names, are not considered.
The above is an interesting JavaScript question: extracting the content of the domain name from the URL. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!