如何使用 jquery 从 url 中提取主机名
how to Extract hostname from url using jquery
这是 URL 示例。
1) domain.com/our-work/insights/tips-and-advice/2008/02/04/the-path-to-good-design-is-proper-analytics
2) subdomain.domain.com
3) im.domain.com/About.htm
4) domain.uk/help.htm
得到这样的结果
domain.com
domain.uk
您可以通过
获取主机名
window.location.hostname
为此,您只需使用 String.prototype.split()
method with /
as delimiter to extract the hostname and then you take the end of the hostname (that contains a dot) with String.prototype.match()
:
var m = url.split('/')[0].match(/[^.]+\.[^.]+$/);
if (m)
var domain = m[0];
注意:如果 url 以方案开头,您需要先将其删除:
var pat = '^https?://';
url = url.replace(new RegExp(pat, 'i'), '');
另一种方法是直接查找域:
var pat = '^(?:https?://)?(?:[^/:]*:[^/@]*@)?[^/]*([^./]+\.[^./]+)';
var m = url.match(new RegExp(pat, 'i'));
if (m)
var domain = m[1];
但在这种情况下,您需要处理主机名之前可能的 login/pass 部分。这就是这个子模式的原因:(?:[^/:]*:[^/@]*@)?
我认为这个正则表达式(如果你想使用正则表达式)就可以了:
\w+\.(?=(com|uk))
演示 here.
试试这个。
您可以通过 javascript 函数实现此功能。
var name = document.domain;
你想从子域中找出域名而不是使用这个。
var parts = location.hostname.split('.');
var subdomain = parts.shift();
var upperleveldomain = parts.join('.');
var sndleveldomain = parts.slice(-2).join('.');
alert(sndleveldomain);
这是 URL 示例。
1) domain.com/our-work/insights/tips-and-advice/2008/02/04/the-path-to-good-design-is-proper-analytics
2) subdomain.domain.com
3) im.domain.com/About.htm
4) domain.uk/help.htm
得到这样的结果
domain.com
domain.uk
您可以通过
获取主机名window.location.hostname
为此,您只需使用 String.prototype.split()
method with /
as delimiter to extract the hostname and then you take the end of the hostname (that contains a dot) with String.prototype.match()
:
var m = url.split('/')[0].match(/[^.]+\.[^.]+$/);
if (m)
var domain = m[0];
注意:如果 url 以方案开头,您需要先将其删除:
var pat = '^https?://';
url = url.replace(new RegExp(pat, 'i'), '');
另一种方法是直接查找域:
var pat = '^(?:https?://)?(?:[^/:]*:[^/@]*@)?[^/]*([^./]+\.[^./]+)';
var m = url.match(new RegExp(pat, 'i'));
if (m)
var domain = m[1];
但在这种情况下,您需要处理主机名之前可能的 login/pass 部分。这就是这个子模式的原因:(?:[^/:]*:[^/@]*@)?
我认为这个正则表达式(如果你想使用正则表达式)就可以了:
\w+\.(?=(com|uk))
演示 here.
试试这个。
您可以通过 javascript 函数实现此功能。
var name = document.domain;
你想从子域中找出域名而不是使用这个。
var parts = location.hostname.split('.');
var subdomain = parts.shift();
var upperleveldomain = parts.join('.');
var sndleveldomain = parts.slice(-2).join('.');
alert(sndleveldomain);