[英]Replace nth match of matches with regex
I'm trying to find a way to replace nth match of more matches lite this. 我正试图找到一种方法来替换更多匹配的第n场比赛。
string = "one two three one one"
How do I target the second occurence of "one"? 我如何针对“一”的第二次出现?
Is it possible to do something like this? 可以这样做吗?
string.replace(/\bone\b/gi{2}, "(one)")
to get something like this 得到这样的东西
"one two three (one) one"
I've done a jsfiddle which is working but it doesn't feel right. 我做了一个正在运作的jsfiddle,但感觉不对。 Heaps of code and confusing for a simple thing. 大量的代码和混淆一个简单的事情。
https://jsfiddle.net/Rickii/7u7pLqfd/ https://jsfiddle.net/Rickii/7u7pLqfd/
Update : 更新:
To make it dynamic use this: 为了使它动态使用:
((?:.*?one.*?){1}.*?)one
where the value 1 means (n-1); 值1表示(n-1); which in your case is n=2 在你的情况下,n = 2
and replace by: 并替换为:
$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);
A more general approach would be to use the replacer function. 更通用的方法是使用替换器功能。
// Replace the n-th occurrence of "re" in "input" using "transform" function replaceNth(input, re, n, transform) { let count = 0; return input.replace( re, match => n(++count) ? transform(match) : match); } console.log(replaceNth( "one two three one one", /\\bone\\b/gi, count => count ===2, str => `(${str})` )); // Capitalize even-numbered words. console.log(replaceNth( "Now is the time", /\\w+/g, count => !(count % 2), str => str.toUpperCase()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.