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.
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
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With