How can I parse a URL string and extract the domain name from it? For a given URL string, how do I 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. There may be many types of protocols, such as http, https, or even more new protocols, therefore, if all protocol names are matched, the scalability is too poor.
However, no matter what your agreement is, this paragraph is indispensable --"://".
In addition, this string is followed by the domain name. We can perform string truncation.
The following code is described in detail:
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; // part after the Protocol name. // github.com/url = url. slice (pos);} // use the decimal point as the segmentation var array = url. split (". "); // if it starts with 3 W, the second part is returned // For example: www.github.com if (array [0] =" www ") {return array [1];} // if it does not start with 3 W, the first part is returned. // For example, github.com/return array [0];}
This method takes into account only a few general situations, such as subdomain names.
The above is JavaScript fun: extract the content of the domain name from the URL. For more information, see PHP Chinese Network (www.php1.cn )!