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
Add a ment  | 

2 Answers 2

Reset to default 5

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./")        == "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