Description:
Write a function that when given a URL as a string, parses out just the domain name and returns it as a string.
For example:
console.log(domainName("http://github.com/carbonfive/raygun")); //"github"
console.log(domainName("http://www.zombie-bites.com")); //"zombie-bites"
console.log(domainName("https://www.cnet.com")); // "cnet"
console.log(domainName('mailto:user@foo.example'')); // "foo"
使用正则解决该问题比较方便
- my answer
function domainName(url){
if (/www./.test(url) == true) {
url.match(/www.([w-]+)/);
return RegExp.$1;
} else if (////.test(url) == true) {
url.match(///([w-]+)/);
return RegExp.$1;
} else {
url.match(/([w-]+)./);
return RegExp.$1;
}
}
- best answer
function domainName(url){
url = url.replace("https://", '');
url = url.replace("http://", '');
url = url.replace("www.", '');
return url.split('.')[0];
};