gpt4 book ai didi

javascript - 并非对所有匹配项都执行正则表达式替换

转载 作者:行者123 更新时间:2023-11-29 16:58:58 25 4
gpt4 key购买 nike

谁能看出为什么以下代码不对所有 {{ ... }} 占位符执行正则表达式操作?下面的输入字符串只是原始字符串的精简版本。

https://jsfiddle.net/2L12jr3u/2/

var input = "{{ %1$@ }} / {{ %1$@ }} ({{ %2$@ }}) {{ %1$@ }} {{ %1$@ }} {{ %1$d }} {{ %1$@ }} of {{ %2$d }} of {{ %3$d }}";

var regex = /(\{\{ \%(\d)\$(.) \}\})/g;

var match;
while (match = regex.exec(input)) {
console.log(match);
input = input.replace(match[0], '%@' + match[2]);
}

console.log(input);

最佳答案

这是因为您更改了input 变量,而exec 还没有完成。索引在向前移动,但字符串变短了。

添加另一个变量,或者包装在一个单独的函数中,或者按照@dfsq 的建议使用replace:

var input = "{{ %1$@ }} / {{ %1$@ }} ({{ %2$@ }}) {{ %1$@ }} {{ %1$@ }} {{ %1$d }} {{ %1$@ }} of {{ %2$d }} of {{ %3$d }}";

var regex = /(\{\{ \%(\d)\$(.) \}\})/g;
var output = input;
var match;

while (match = regex.exec(input)) {
console.log(match);
output = output.replace(match[1], '%@' + match[2]);
}

alert(output);

关于javascript - 并非对所有匹配项都执行正则表达式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29833245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com