JS:从url获取主机名,正则表达式无效

时间:2014-08-14 07:01:23

标签: javascript jquery regex replace

我正在尝试从我的webapp可以遇到的一组网址获取主机名。 所需的输出应该类似http://localhost/Webapp/,结束于/Webapp/,之后的所有内容都应删除。

请注意,我不想在正则表达式中使用单词Webapp,因为此名称是动态的,仅用于演示/测试用例。这可以是任何东西,而不是用于编码。

在实例中我使用的是location.href.replace(/index.+/g, "").replace(/#.+/g, "") 我希望只保留主机名以Webapp/结尾。

问题: 我的解决方案似乎工作正常,除了"http://localhost/Webapp/#"无法正常工作?这是为什么 ?看下面的小提琴

JSFIDDLE http://jsfiddle.net/bababalcksheep/um0uqb8v/ JS:

var getHost = function (url) {
    return url.replace(/index.+/g, "").replace(/#.+/g, "")
};
var urls = [
     "http://localhost/Webapp/",
    "http://localhost/Webapp/#",
    "http://localhost:8080/Webapp/#sdf#dfgdf#fdg",
    "12.168.1.1:8080/Webapp/index.html#",
    "https://localhost/Webapp/index.html#ab#bg",
    "https://localhost/Webapp/index.html"
];
//Print all urls
$.each(urls, function () {
    $("<p/>").text(getHost(this)).appendTo($(".test"));
});

3 个答案:

答案 0 :(得分:4)

使用url.match(/https?:\/\/([^\/]+)/);

修改

它返回一个数组,其中第一个元素是具有协议的主机,第二个元素是没有的主机。

答案 1 :(得分:3)

您可以使用一些技巧让浏览器为您提取主机名。

var getHost = function (url) {
    var a = document.createElement('a');
    a.href = url;
    return a.hostname;
};

您似乎也想要这条路径。您可以使用pathname元素的a属性访问它。如果您正在执行此操作,则应将该功能重命名为getHostAndPath()

答案 2 :(得分:3)

您可以尝试删除最后一个斜杠(文件和散列)之后的任何内容:

var getHost = function (url) {
    return url.replace(/\/[^/]*?$/, '/');
};

here's the updated fiddle