I\'m trying to find a way to replace nth match of more matches lite this.
string = \"one two three one one\"
How do I target the se
Update :
To make it dynamic use this:
((?:.*?one.*?){1}.*?)one
where the value 1 means (n-1); which in your case is n=2
and replace by:
$1\(one\)
Regex101 Demo
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()));