JavaScript正则表达式:去除URL中的最后一部分 - 即最后一个斜杠后面的内容。

4

我需要一个JS正则表达式来弹出URL的最后一部分。但是,如果它只是域名,比如http://google.com,我不想改变任何东西。

以下是示例。非常感谢您的帮助。

http://google.com -> http://google.com
http://google.com/ -> http://google.com
http://google.com/a -> http://google.com
http://google.com/a/ -> http://google.com/a
http://domain.com/subdir/ -> http://domain.com/subdir
http://domain.com/subfile.extension -> http://domain.com
http://domain.com/subfilewithnoextension -> http://domain.com
2个回答

5
我发现不使用正则表达式会更简单。
var removeLastPart = function(url) {
    var lastSlashIndex = url.lastIndexOf("/");
    if (lastSlashIndex > url.indexOf("/") + 1) { // if not in http://
        return url.substr(0, lastSlashIndex); // cut it off
    } else {
        return url;
    }
}

示例结果:

removeLastPart("http://google.com/")        == "http://google.com"
removeLastPart("http://google.com")         == "http://google.com"
removeLastPart("http://google.com/foo")     == "http://google.com"
removeLastPart("http://google.com/foo/")    == "http://google.com/foo"
removeLastPart("http://google.com/foo/bar") == "http://google.com/foo"

4

我利用了DOM中的HTMLAnchorElement

function returnLastPathSegment(url) {
   var a = document.createElement('a');
   a.href = url;

    if ( ! a.pathname) {
        return url;
    }

    a.pathname = a.pathname.replace(/\/[^\/]+$/, '');
    return a.href;
}

jsFiddle.


请注意,Internet Explorer似乎没有包含前导斜杠,因此您需要考虑这一点。 - Sasha Chedygov
@musicfreak 这似乎没有影响它(除非我做错了什么)。jsFiddle - alex
不不不,你没有做错任何事,我只是在记录下来,以防有人想要采用这个想法去做其他的事情。对于误解,我感到抱歉。 - Sasha Chedygov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接