admin管理员组文章数量:1355969
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 , I don't want anything changed.
Below are examples. Any help is greatly appreciated.
->
/ ->
->
/ ->
/ ->
.extension ->
->
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., I don't want anything changed.
Below are examples. Any help is greatly appreciated.
http://google. -> http://google.
http://google./ -> http://google.
http://google./a -> http://google.
http://google./a/ -> http://google./a
http://domain./subdir/ -> http://domain./subdir
http://domain./subfile.extension -> http://domain.
http://domain./subfilewithnoextension -> http://domain.
Share
Improve this question
asked Jun 12, 2011 at 2:58
Mike BeepoMike Beepo
792 silver badges5 bronze badges
2 Answers
Reset to default 5I 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./") == "http://google."
removeLastPart("http://google.") == "http://google."
removeLastPart("http://google./foo") == "http://google."
removeLastPart("http://google./foo/") == "http://google./foo"
removeLastPart("http://google./foo/bar") == "http://google./foo"
I took advantage of the HTMLAnchorElement
in the 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.
本文标签: Javascript Regex to get rid of last part of URLafter the last slashStack Overflow
版权声明:本文标题:Javascript Regex to get rid of last part of URL - after the last slash - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743938524a2565131.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论