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

问题描述

| 本质上,我需要一个JS Regexp来弹出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
    

解决方法

        我利用了DOM中的ѭ1。
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。     ,        我发现不使用正则表达式就更简单了。
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\"