Reputation: 73
How can I find and replace for example every third occurrence of 'x' character in string with regular expression?
There is similar question but it addresses every fourth character but I need every "nth" occurrence of specific character in string.
I'm using JavaScript replace()
method, this below example will change every x character to y:
replace(/\x/g, 'y')
But how can I write regex for question above?
Some random text for example, and expected result:
I amx nexver axt hoxme on Sxundxaxs.
to:
I amx nexver ayt hoxme on Sxundyaxs.
I can use JS for
loop with split()
and join()
but solution with replace()
method seams more elegant.
Upvotes: 7
Views: 13363
Reputation: 784998
You can use:
str = str.replace(/((?:[^x]*x){2}[^x]*)x/g, '$1y');
So if you are searching for every 3rd occurrence then use n-1
between {}
in above regex.
To build it dynamically use:
let str = 'I amx nexver axt hoxme on Sxundxaxs';
let n = 3;
let ch = 'x';
let regex = new RegExp("((?:[^" +ch+ "]*" +ch+ "){" + (n-1) + "}[^" +ch+ "]*)" +ch, "g");
str = str.replace(regex, '$1y');
console.log(str);
//=> I amx nexver ayt hoxme on Sxundyaxs
Upvotes: 14