Javascript Regex, чтобы избавиться от последней части URL - после последней косой черты - PullRequest
4 голосов
/ 12 июня 2011

По сути, мне нужен JS Regexp, чтобы выскочить из последней части URL.Суть в том, что если это просто доменное имя, например http://google.com,, я не хочу ничего менять.

Ниже приведены примерыЛюбая помощь с благодарностью.

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

Ответы [ 2 ]

5 голосов
/ 12 июня 2011

Я нашел это проще без использования регулярных выражений.

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;
    }
}

Пример результатов:

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"
4 голосов
/ 12 июня 2011

Я воспользовался HTMLAnchorElement в 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 .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...