【问题标题】:jQuery: Replace multiple regex matches with string?jQuery:用字符串替换多个正则表达式匹配?
【发布时间】:2010-01-03 03:03:36
【问题描述】:

我正在尝试使用此代码块将长字符串中的所有“123”替换为不同的数字。

   var new_id = new Date().getTime();
    $('#food').after(
      "<div id='123' name='123'> etc etc".replace('123', new_id)
    );

但它只是将前 123 替换为 new_id。有没有办法全部替换?

【问题讨论】:

    标签: javascript jquery regex


    【解决方案1】:

    您需要将其设为正则表达式而不是普通的原版字符串,并添加 /g 标志。

    "<div id='123' name='123'> etc etc".replace(/123/g, new_id)
    

    【讨论】:

      【解决方案2】:

      replace(/123/g, new_id)

      这是带有全局 (g) 标志的 regex literal syntax

      【讨论】:

        猜你喜欢
        • 2012-01-25
        • 2015-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-30
        • 2022-12-01
        • 1970-01-01
        相关资源
        最近更新 更多