我有一个字符串,我正尝试使用如下正则表达式进行操作:
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/