【问题标题】:How do I replace multiple items in a string?如何替换字符串中的多个项目?
【发布时间】:2011-06-23 15:16:30
【问题描述】:

起始字符串:

I like [dogs], [cats], and [birds]

需要的最终输出:

I like <a href="#">dogs</a>, <a href="#">cats</a>, and <a href="#">birds</a>

所以基本上将带括号的项目更改为链接。

【问题讨论】:

    标签: javascript regex replace


    【解决方案1】:

    使用这个表达式:

    var str = 'I like [dogs], [cats], and [birds]';
    alert(str.replace(/\[(.+?)\]/g, '<a href="#">$1</a>'));
    
    • \[(.+?)\] 请求文字 [,以延迟匹配并捕获任何内容,然后匹配文字 ]。替换为 &lt;a&gt; 标签中所捕获的内容。

    • g 修饰符表示全局替换,即查找并替换每个匹配项,而不仅仅是第一个匹配项。

    jsFiddle preview

    【讨论】:

    • @Trufa:我想说,远非如此。
    • 那是“?”的原因,评论不见了!
    • 很好的解决方案。完美运行。
    【解决方案2】:

    这是一个简单的字符串替换。

    function tagIt(source)
    {
      return source.replace('[', '<a href="#">').replace(']', '</a>');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 2011-09-01
      • 2012-03-12
      • 2022-01-03
      相关资源
      最近更新 更多