我正在尝试找到一种方法来替换更多比赛的第n场比赛。
string = "one two three one one"
如何定位第二次出现的“一”?
可以做这样的事情吗?
string.replace(/\bone\b/gi{2}, "(one)")
得到这样的东西
"one two three (one) one"
我做了一个 jsfiddle ,它可以工作,但感觉不对。一堆代码让简单的事情变得混乱。
https://jsfiddle.net/Rickii/7u7pLqfd/ https://jsfiddle.net/Rickii/7u7pLqfd/
Update :
要使其动态,请使用以下命令:
((?:.*?one.*?){1}.*?)one
其中值 1 表示 (n-1);在你的情况下是 n=2
并替换为:
$1\(one\)
Regex101 演示 https://regex101.com/r/lIJ3I7/4
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)