我正在尝试找到一种方法来替换更多匹配项中的第 n 个匹配项。
string = "one two three one one"
如何定位第二次出现的“one”?
有没有可能做这样的事情?
string.replace(/\bone\b/gi{2}, "(one)")
得到这样的东西
"one two three (one) one"
我做了一个 jsfiddle,它可以工作,但感觉不对。一堆代码和简单的事情令人困惑。
最佳答案
更新:
要使其动态使用:
((?:.*?one.*?){1}.*?)one
其中值 1 表示 (n-1);在你的情况下是 n=2
并替换为:
$1\(one\)
const regex = /((?:.*?one.*?){1}.*?)one/m;
const str = `one two three one one asdfasdf one asdfasdf sdf one`;
const subst = `$1\(one\)`;
const result = str.replace(regex, subst);
console.log( result);
关于javascript - 用正则表达式替换第 n 个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42943096/