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:
- 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, 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:
- function domainName(url){
- var sign = "://";
- var pos = url.indexOf(sign);
- //if it starts with the protocol name
- //Such as: 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 it starts with 3W, return to the second part
- //Such as: www.github.com
- if(array[0] === "www"){
- return array[1];
- }
- //If it doesn't start with 3W, return the first part
- //Such as: github.com/
- return array[0];
- }
This method only considers several general situations, and some situations, such as subdomains, are not considered.
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;
}