Mik*_*epo 4 javascript regex 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
Run Code Online (Sandbox Code Playgroud)
小智 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;
}
}
Run Code Online (Sandbox Code Playgroud)
示例结果:
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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5408 次 |
| 最近记录: |