I have a string and I want to remove the first 3 occurrences of the letter a
(for example).
Seems regex has no solution for a specific number of occurrences. And I can't use replace
without loops, which I want to avoid.
Nice challenge.
This works:
var str = "I have a string and I want to remove the first 3 occurrences of the letter a (for example).";
str = str.replace(/^([^a]*a){3}/, function(match) {
return match.replace(/a/g, '!');
});
document.body.innerHTML = str;
Result:
I h!ve ! string !nd I want to remove the first 3 occurrences of the letter a (for example).
The first replace
matches a continuous string containing exactly 3 a
s. Its inner replace changes the a
to a !
for clarity; you can safely replace it with nothing as well.
This is scaleable to any number because you can change the {3}
to the required number of changes.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments