【问题标题】:Javascript remove url last segment if found is numeric如果找到的是数字,Javascript 会删除 url 最后一段
【发布时间】:2018-03-02 06:43:35
【问题描述】:

我有 javascript 函数来映射 url 和超链接以突出显示菜单项,但是我不能在更深的页面中使用 url 最后一段带有数字,url 看起来像:http://localhost/story/89

如果最后一个 url 段是一个数字,我想删除它,因此该 url 将以 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];
}

【问题讨论】:

  • 你这样做有什么意义?

标签: javascript url segment


【解决方案1】:

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

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

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

更多关于正则表达式here

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

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

【讨论】:

    【解决方案2】:
        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'));

    【讨论】:

      【解决方案3】:

      function validateURL(url){ let lastSegment = url.split("/");if(lastSegment[(lastSegment.length)-1].match(/^[0-9]$/))console.log (“真正的最后一段”); } validateURL("http://localhost/demo/8");

      【讨论】:

      • 为了验证最后一段,你可以使用下面的代码:
      猜你喜欢
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 2012-08-28
      • 2013-03-24
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      相关资源
      最近更新 更多