2011-06-12 48 views
4

本质上,我需要一个JS正则表达式来弹出URL的最后部分。它的好处在于,虽然它只是域名,比如http://google.com,但我不想要任何改变。Javascript正则表达式来摆脱URL的最后部分 - 在最后一个斜杠后

下面是例子。任何帮助是极大的赞赏。

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 

回答

4

我趁着HTMLAnchorElement在DOM。

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

+0

谢谢,对我很好。 – 2011-06-12 05:22:24

+0

请注意,Internet Explorer似乎没有包含前导斜杠,因此您必须对此进行说明。 – 2012-03-18 21:01:28

+0

@musicfreak这似乎没有影响它(除非我做错了什么)。 [的jsfiddle](http://jsfiddle.net/sYM3x/)。 – alex 2012-03-18 21:07:56

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" 
相关问题