Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

js 获取网站的根域名

如:在 www.baidu.com获取 baidu.com

a.baidu.com 获取 baidu.com
可能有很多人没有明白我的意思,这的难点是不可能用正则获取匹配截取获取根域名的
比如www.a.china.com.cn你怎么知道截取的是china.com.cn呢??
所以我感觉应该有个域名库然后在匹配吧。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

把 host 按 . 分割,length 为 2,不用处理,大于 2 的去掉数组首位。

var hostArr = location.host.split('.')
hostArr.length === 2 ? hostArr.join('.') : hostArr.slice(1).join('.')

哦,不对。我没有考虑到三级域名...还是需要一个特征库匹配。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...