javascript - RegExp exec - 字符串操作

标签 javascript regex

我有一个字符串,我正尝试使用如下正则表达式进行操作:

var str = 'This is a string with 1: {{param1}}, 2: {{param2}} and 3: {{param3}}',
    reg = /{{.*?}}/ig;

while (field = reg.exec(str)) {
    str = str.replace(field, 'test');
}

{{param2}} 永远不会被替换 - 我的猜测是因为我在通过 RegExp.exec(...) 运行字符串时对其进行了操作。但不能确定。

我已经尝试了以下方法(因为我注意到 RegExp.exec(...) 返回一个数组)——仍然没有成功:

var str = 'This is a string with 1: {{param1}}, 2: {{param2}} and 3: {{param3}}',
    reg = /{{.*?}}/ig;

while (field = reg.exec(str)) {
    str = str.replace(field[0], 'test');
}

有什么想法吗?

编辑这个函数的当前结果是:

'This is a string with 1: test, 2: {{param2}}, test and 3: test'

最佳答案

您应该删除 g 标志。

var str = 'This is a string with 1: {{param1}}, 2: {{param2}} and 3: {{param3}}',
    reg = /{{.*?}}/; 



while (field = reg.exec(str)) {
    str = str.replace(field, 'test');
    console.log(str)
}

结果:

第一次迭代:

This is a string with 1: test, 2: {{param2}} and 3: {{param3}}

第二个:

This is a string with 1: test, 2: test and 3: {{param3}}

第三个:

This is a string with 1: test, 2: test and 3: test

另一种选择是:

 str = str.replace(/{{.*?}}/g, 'test');

这也会产生:

This is a string with 1: test, 2: test and 3: test

编辑:

添加到 Anonymous 的答案中:

问题是每个replace - 都会使原始字符串更短。索引是在开始用原始较长的行计算的。

换句话说,如果您想替换为与 {{param1}} 相同长度的表达式(它的长度为 9),替换为另一个长度相同为 9 的字符串,例如:**test1** ,那么你的代码就可以工作了:

var str = 'This is a string with 1: {{param1}}, 2: {{param2}} and 3: {{param3}}',
    reg = /{{.*?}}/g


while (field = reg.exec(str)) {

    str = str.replace(field, '**test1**');
    console.log(str)
}

结果:

This is a string with 1: **test1**, 2: **test1** and 3: **test1**

关于javascript - RegExp exec - 字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31942145/

相关文章:

javascript - 如何在 React 中更新 parent 的状态?

javascript - 删除父 Div 以在没有样式的情况下正确显示表单输入元素

javascript - Protractor firefox 控制台日志错误未出现

regex - sed - 跨多个文件删除某些字符串的部分

regex - Vim 用 unicode 字符替换

java - 使用正则表达式将符号添加到字母数字检查

javascript - 通过 javascript 显示文本而不是选择的值下拉列表

javascript - 为什么我必须包含 JS 文件才能在每个 View 中使用 jquery?

python - 不可能的反向引用

python - 以 ABC 开头,然后是 B 和/或 C,并以 CBA 结尾的模式的正则表达式