从 URL 中提取域名


DESCRIPTION

Write a function that when given a URL as a string, parses out just the domain name and returns it as a string.

SOLUTION

  • 方法一:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function domainName(url) {
let domain;
// find & remove protocol (http, ftp, etc.) and get domain
if (url.indexOf("://") > -1) {
domain = url.split("/")[2];
} else {
domain = url.split("/")[0];
}
// remove port number if any
domain = domain.split(":")[0];
// remove www if any
domain = domain.replace("www.", "");
// remove .com if any
domain = domain.replace(".com", "");
return domain.split(".")[0];
}
  • 方法二:先删除域名前的字符串然后根据 . 分割,第一个就是我们要的域名啦!
1
2
3
4
5
6
function domainName(url) {
url = url.replace("https://", "");
url = url.replace("http://", "");
url = url.replace("www.", "");
return url.split(".")[0];
}

Reference

Extract the domain name from a URL