开发者

Javascript Regex to get rid of last part of URL - after the last slash

开发者 https://www.devze.com 2023-03-12 12:42 出处:网络
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 htt开发者_StackOverflowp://google.com, I don\'t want anything changed.

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 htt开发者_StackOverflowp://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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号