Home > Web Front-end > JS Tutorial > JavaScript fun question: Extract domain name from URL

JavaScript fun question: Extract domain name from URL

黄舟
Release: 2017-01-22 14:48:15
Original
1441 people have browsed it

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"
Copy after login

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];  
}
Copy after login

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)!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template