【问题标题】:how to get javascript replace function to match each occurence and not just the outer occurence如何让javascript替换函数匹配每次出现而不仅仅是外部出现
【发布时间】:2013-01-10 03:20:41
【问题描述】:

给定以下文本:

This <em>is</em> just <em>example</em> text.

我想用\i...\i替换&lt;em&gt;...&lt;/em&gt;所以我尝试了这种替换方法。

replace( /<em>(.+)<\/em>/, "\\i$1\\i" )

但结果文本是:

This \iis</em> just <em>example\i text.

如您所见,它替换了外部匹配项,但中间的 "&lt;/em&gt; just &lt;em&gt;" 保持不变。我希望它替换匹配的每次出现,以便 &lt;em&gt;...&lt;/em&gt; 的每个实例都替换为 \i...\i

【问题讨论】:

    标签: javascript regex replace


    【解决方案1】:

    我们使用? 处理贪婪是什么:

    str.replace(/<em>(.+?)<\/em>/g, "\\i$1\\i");
    
    // >> "This \iis\i just \iexample\i text."
    

    【讨论】:

    • 是的,成功了。现在生成的文本是“This \iis\i just \iexample\i text”。应该是这样。谢谢。
    【解决方案2】:

    试试这个:

    "This <em>is</em> just <em>example</em> text.".replace(/<\/?em>/gi, "\\i");
    

    解释:

    /<\/?em>/gi
    

    /gi全局并忽略大小写(接受“​​em”、“Em”、“eM”、“EM”,你懂的)

    \/? 带或不带 /

    【讨论】:

    • 这也将替换未配对的标签——尽管我不知道操作是否关心
    • 是的,但是他想替换任何一个,这不是主意吗?如果你有一个未闭合的标签,将创建一个未闭合的 \i... 这不是一个真正的问题...
    猜你喜欢
    • 2016-09-08
    • 2021-01-10
    • 1970-01-01
    • 2016-01-23
    • 2016-12-15
    • 2022-10-13
    • 2019-08-24
    • 1970-01-01
    • 2014-01-28
    相关资源
    最近更新 更多