【问题标题】:Replacing string in multiline variable not working [duplicate]替换多行变量中的字符串不起作用[重复]
【发布时间】:2017-10-11 23:48:31
【问题描述】:

我正在尝试替换以下变量中的字符串{NUM}

var table = '        <table class="full-width">\r\n' +
            '            <tbody>\r\n' +
            '            <tr>\r\n' +
            '                <td width="75%" class="border-right-dotted left-line-tab">\r\n' +
            '                    <span id="47_TOTAL-CHARGES_D_{NUM}" class="input-text"></span>\r\n' +
            '                </td>\r\n' +
            '                <td width="25%" class="center-text">\r\n' +
            '                    <span id="47_TOTAL-CHARGES_C_{NUM}" class="input-text"></span>\r\n' +
            '                </td>\r\n' +
            '            </tr>\r\n' +
            '            </tbody>\r\n' +
            '        </table>\r\n';

使用以下 jquery 替换: table = table.replace("/{NUM}/gm", num);

但它似乎不起作用。在https://regex101.com/ 中测试正则表达式似乎表明该正则表达式没问题,但它仍然没有按预期替换文本。

【问题讨论】:

  • 您正在寻找字符串文字;你没有使用正则表达式。删除引号:table.replace(/{NUM}/gm, num);

标签: javascript jquery regex replace


【解决方案1】:

只需去掉双引号:

table = table.replace(/{NUM}/gm, num);

双引号内的文本定义了一个字符串文字,而您需要一个正则表达式文字,它应该用斜杠括起来。

【讨论】:

  • 我觉得自己好蠢!非常感谢。
猜你喜欢
  • 1970-01-01
  • 2011-09-07
  • 2017-07-25
  • 2013-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多