Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 709
Mike Beepo Avatar asked Jan 20 '23 12:01

Mike Beepo


2 Answers

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"
like image 80
Jeremy Avatar answered Feb 15 '23 09:02

Jeremy


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.

like image 20
alex Avatar answered Feb 15 '23 11:02

alex