Javascript正则表达式摆脱URL的最后部分 - 在最后一个斜杠之后

时间:2022-10-20 10:04:33

Essentially I need a JS Regexp to pop off the last part of a URL. The catch of it is, though if it's just the domain name, like http://google.com, I don't want anything changed.

基本上我需要一个JS Regexp来弹出URL的最后一部分。它的关键是,虽然它只是域名,如http://google.com,我不希望任何改变。

Below are examples. Any help is greatly appreciated.

以下是示例。任何帮助是极大的赞赏。

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 个解决方案

#1


4  

I took advantage of the HTMLAnchorElement in the DOM.

我利用了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.

#2


5  

I found this simpler without using regular expressions.

我发现这个更简单,不使用正则表达式。

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

Example results:

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"

#1


4  

I took advantage of the HTMLAnchorElement in the DOM.

我利用了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.

#2


5  

I found this simpler without using regular expressions.

我发现这个更简单,不使用正则表达式。

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

Example results:

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"