使用JavaScript获取没有子域名的域名? [英] Get domain name without subdomains using JavaScript?

查看:131
本文介绍了使用JavaScript获取没有子域名的域名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取没有子域名的域名?

How to get the domain name without subdomains?

例如。如果网址是 http://one.two.roothost.co.uk/page。 html 如何获取roothost.co.uk?

e.g. if the url is "http://one.two.roothost.co.uk/page.html" how to get "roothost.co.uk"?

推荐答案

以下是提取域名的解决方案没有任何子域名的名称。此解决方案不对URL格式做任何假设,因此它适用于任何URL。由于某些域名有一个后缀( .com ),有些域名有两个或更多( .co.uk )为了在所有情况下获得准确的结果,我们需要使用公共后缀列表解析主机名,其中包含一个列表所有公共域名后缀。

Following is a solution to extract a domain name without any subdomains. This solution doesn't make any assumptions about the URL format, so it should work for any URL. Since some domain names have one suffix (.com), and some have two or more (.co.uk), to get an accurate result in all cases, we need to parse the hostname using the Public Suffix List, which contains a list of all public domain name suffixes.

首先,在脚本中包含公开后缀列表js api 在HTML中标记,然后在JavaScript中获取可以调用的主机名:

First, include the public suffix list js api in a script tag in your HTML, then in JavaScript to get the hostname you can call:

var parsed = psl.parse('one.two.roothost.co.uk');
console.log(parsed.domain);

...将返回roothost.co.uk。要从当前页面获取名称,您可以使用 location.hostname 而不是静态字符串:

...which will return "roothost.co.uk". To get the name from the current page, you can use location.hostname instead of a static string:

var parsed = psl.parse(location.hostname);
console.log(parsed.domain);

最后,如果您需要直接从完整的URL字符串解析域名,您可以使用以下内容:

Finally, if you need to parse a domain name directly out of a full URL string, you can use the following:

var url = "http://one.two.roothost.co.uk/page.html";
url = url.split("/")[2]; // Get the hostname
var parsed = psl.parse(url); // Parse the domain
document.getElementById("output").textContent = parsed.domain;

JSFiddle示例(它包含jsFiddle中的整个缩小库,所以向下滚动!): https://jsfiddle.net/6aqdbL71/2/

JSFiddle Example (it includes the entire minified library in the jsFiddle, so scroll down!): https://jsfiddle.net/6aqdbL71/2/

这篇关于使用JavaScript获取没有子域名的域名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆