如果找到数字,则javascript删除网址最后一段

时间:2017-09-21 03:29:49

标签: javascript url segment

我有javascript函数来映射网址和超链接以突出显示菜单项,但是我无法在更深的页面中执行此操作,其中url最后一个段带有数字,网址如下:http://localhost/story/89

我想删除最后一个网址段,如果它是一个数字,那么网址最终会http://localhost/story(条带/)。

/* highlight nav menu */
$(function(){
    $('#topMain li a').each(function(index) {
        if($.trim(this.href) == stripQueryStringAndHashFromPath(window.location.href)) {
            $(this).closest('li').addClass('active')
            .closest('li.parent').addClass('active');
        }
    });
});

function stripQueryStringAndHashFromPath(url) {
    return url.split("?")[0].split("#")[0];
}

3 个答案:

答案 0 :(得分:1)

您可以将正则表达式参数传递给split()

只需将.split(/(\/\d*)$/)[0]添加到url.split("?")[0].split("#")[0]函数中stripQueryStringAndHashFromPath的末尾。

正则表达式的新段基本上搜索反斜杠(\/),后跟一个或多个数字(\d*),位于末尾($)一个字符串。

有关正则表达式here的更多信息。

function stripQueryStringAndHashFromPath(url) {
    url = url.split('?')[0].split('#')[0].split(/(\/\d*)$/)[0];
    return url;
}

console.log(stripQueryStringAndHashFromPath('http://localhost/story/89'));

答案 1 :(得分:0)

    function validateURL(url){ let lastSegment = url.split("/");
        if(lastSegment[(lastSegment.length)-1].match(/^[0-9]$/))
            console.log("True Last Segmant");
        }
    validateURL("http://localhost/demo/8")



function stripQueryStringAndHashFromPath(url) {
    url = url.split('?')[0].split('#')[0].split(/(\/\d*)$/)[0];
    return url;
}

console.log(stripQueryStringAndHashFromPath('http://localhost/story/89'));




答案 2 :(得分:0)

function validateURL(url){let lastSegment = url.split(" /"); if(lastSegment [(lastSegment.length)-1] .match(/ ^ [0-9] $ /))console.log("True Last Segmant"); } validateURL(" http://localhost/demo/8");