JavaScript fun: extract domain names from URLs

Source: Internet
Author: User
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 )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.