正则表达式找到没有www的域名

时间:2013-07-02 13:59:40

标签: javascript

我想获得没有www

的域名

ex:https://www.gmail.com/anything 输出应该是gmail.com(或.net或.org)

任何人都可以帮我制作正则表达式吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

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

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;
}

DEMO: http://jsfiddle.net/DuK6D/


More info/attributes about the HTMLAnchorElement JS object on MDN