Reputation: 975
I have a string like 'a b b b a' and want to replace every 'b' in that string that has a whitespace before and after the character with a different character. How could I do that with a regex? My idea was this:
'x a y a x'.replace(new RegExp(' a ', 'g'), ' b '); // is: x b y b x, should: x b y b x (correct)
'x a a a x'.replace(new RegExp(' a ', 'g'), ' b '); // is: x b a b x, should: x b b b x (wrong)
'x aa x'.replace(new RegExp(' a ', 'g'), ' b '); // is: x aa x, should: x aa x (correct)
But that regex is only working if there is not more than 1 occurence of the character next to another occurence of the character. How could I write the regex to get the right behaviour?
Upvotes: 4
Views: 2544
Reputation: 2708
You can use RegExp with g
flag with the replace
method. Try this
var mystring = "this is a a a a a a test"
mystring.replace(/ a /g , "b");
Upvotes: 0
Reputation: 786329
As your matches are overlapping, you can use zero width assertion i.e a positive lookahead based regex:
str = str.replace(/( )a(?= )/g, "\1b");
( )a
will match a space before a
and capture it in group #1 followed by a
(?= )
will assert presence of a space after a
but won't consume it in the match.Upvotes: 3
Reputation: 627600
Use a lookahead after " a" to match overlapping substrings:
/ a(?= )/g
Or, to match any whitespace, replace spaces with \s
.
The lookahead, being a zero-width assertion, does not consume the text, so the space after " a" will be available for the next match (the first space in the pattern is part of the consuming pattern).
See the regex demo
var regex = / a(?= )/g;
var strs = ['x a y a x', 'x a a a x', 'x aa x'];
for (var str of strs) {
console.log(str,' => ', str.replace(regex, " b"));
}
Upvotes: 6