-2

我想得到没有www的域名

例如:https ://www.gmail.com/anything 输出应为 gmail.com(或 .net 或 .org)

任何人都可以帮我为此提供正则表达式吗?

4

2 回答 2

4

使用正则表达式,例如/(?:https?:\/\/)?(?:www\.)?(.*?)\//

var str = "https://www.gmail.com/anything";
var match = str.match(/(?:https?:\/\/)?(?:www\.)?(.*?)\//);
console.log(match[match.length-1]); //gmail.com (last group of the match)

注意:这将获取 http/https 协议之后的所有内容,不包括 www - 直到第一个斜杠。

额外说明:很多域使用子域 - 因此mail.google.com会突然变成google.com并且因此不起作用。我的包括.www

于 2013-07-02T14:04:30.190 回答
3

您可以使用 a<a>获取有关 URL 的信息。例如:

var a = document.createElement("a");
a.href = "http://www.google.com";

您可以使用以下方法检索域:

var domain = a.hostname;

你可以去掉任何领先的“www.”:

domain = domain.replace(/^www\./, "");

作为可重用的功能,您可以使用:

function getDomain(url) {
    var a, domain;

    a = document.createElement("a");
    a.href = url;

    domain = a.hostname;
    domain = domain.replace(/^www\./, "");

    return domain;
}

演示:http: //jsfiddle.net/DuK6D/


有关 MDN 上 HTMLAnchorElement JS 对象的更多信息/属性

于 2013-07-02T14:22:44.593 回答