【问题标题】:Replace last forward slash in string with other character用其他字符替换字符串中的最后一个正斜杠
【发布时间】:2014-02-19 17:33:08
【问题描述】:

我正在尝试替换一系列 url 字符串中的最后一个正斜杠,以将该正斜杠替换为数字符号,就像这样 -

http://example.com/about/our-company

http://example.com/about#our-company

在 jQuery 中使用 JS 我尝试在每个字符串上应用替换功能,但不确定如何仅定位最后一个正斜杠。

$('.submenu a').each(function() {
    var url = $(this).attr('href');
    url = url.replace(/\//g, '#');
    console.log(url);
    // replaces all
});

【问题讨论】:

    标签: javascript jquery regex replace


    【解决方案1】:

    试试这个:

    var str = "http://one/two/three/four";
    console.log(str.replace(/\/(?=[^\/]*$)/, '#'));
    

    这就是说:“将后面的斜杠替换为任何内容或不包含另一个斜杠的字符,直到最后。”

    【讨论】:

    • 感谢乌特卡诺斯!这工作得很好,除了我意识到所有的 url 都是在末尾带有斜杠生成的...... doh!假设情况总是如此,是否有类似的方法来定位 second 最后一个正斜杠?我知道,我可能应该用另一种方式来做这件事。
    • 这会使模式变得非常复杂。最简单的方法是首先去掉尾部的斜杠(你可以稍后再添加它)。所以:var str = "http://one/two/three/four/".replace(/\/$/, '');
    • 没错,这可能是最流畅的选择。再次感谢。
    【解决方案2】:

    您可以尝试根据/拆分Url:

    url = 'http://example.com/about/our-company';
    tokens = url.split('/');
    expected_url = tokens.slice(0, tokens.length-1).join('/') + '#' + tokens[tokens.length-1];
    
    console.log(expected_url);
    # Prints 'http://example.com/about#our-company'
    

    【讨论】:

      【解决方案3】:
      $('.submenu a').each(function() {
          var url = $(this).attr('href');
          var idx = url.lastIndexOf("/");
          url = url.substring(0, idx) + '#' + url.substring(idx+1);
          console.log(url);
      });
      

      【讨论】:

        【解决方案4】:

        一个简单的解决方案:

        var str="http://example.com/about/our-company";
        var tmp=str.split("").reverse().join("");
        tmp=tmp.replace("/","#");
        str=tmp.split("").reverse().join("");
        
        //output:
        
        str = http://example.com/about#our-company
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-02-27
          • 1970-01-01
          • 2011-08-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多