【问题标题】:JavaScript: Replace last occurrence of forward slashJavaScript:替换最后一次出现的正斜杠
【发布时间】:2013-05-14 08:31:07
【问题描述】:

我试过摆弄

replace(/_([^_]*)$/,replacement+'$1')

来自另一个帖子,但无法正常工作

我有一个字符串:

<div class="plus"></div><div class="details"></div>text1/text2

我想变成的样子

<div class="plus"></div><div class="details"></div>text1/<br>text2

但我也不断替换 /div 中的 /

有人吗?

编辑:要清楚我想替换最后一个

"/" 

"/<br>"

只有最后一次出现。

我不知道...也许我最好还是回到我的代码中并尝试在添加 html 之前替换斜杠...

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    使用lastIndexOf()方法

    var index = str.lastIndexOf('/');
    str = str.substr(0, index + 1) + "<br>" + str.substr(index + 1);
    

    这里是fiddle

    【讨论】:

    • 也可以工作 - 但再次落后于仅替换 / 如果它不是结束标签的一部分的能力
    • @CJe 然后将您的字符串设为“text1”或“text1/text2”而不是整个标签并执行此操作
    • 完成。然后我可以使用“正常”替换操作。谢谢。
    • @CJe Yupp 你可以正常替换...好
    【解决方案2】:

    试试

    '<div class="plus"></div><div class="details"></div>text1/text2'.replace(/(\/)([^\/]*)$/, '$1' + '<br />' + '$2' )
    

    【讨论】:

    • 这可能有效,但我刚刚意识到并非所有字符串都以包含正斜杠的文本结尾,这意味着例如
      text1 将失败:-(
    【解决方案3】:

    如果您不想在反向引用中捕获斜线,请将斜线添加到文本本身中:

    replace(/_([^_]*)$/,replacement+'$1/')
    -----------------------------------^
    

    【讨论】:

      【解决方案4】:

      使用字符串方法更容易做到这一点:

      var index = str.lastIndexOf('/');
      str = str.substr(0, index) + str.substr(index + 1);
      

      【讨论】:

        猜你喜欢
        • 2023-03-10
        • 1970-01-01
        • 2012-05-17
        • 2021-05-29
        • 2016-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多