Reputation: 2783
Let's say I had the following string Hello World
and I wanted to replace every part of it that does not contain an o
or a space with an x
.
Using regex, I could simply do the following:
var myStr = "Hello World";
console.log(myStr.replace(/[^o ]/g, "x"));
Now, what if I wanted to replace all parts of a string that does not contain the string ll
or a space for example, with an x
?
I tried this but with no luck:
// intended result: xxllx xxxxx
var myStr = "Hello World";
console.log(myStr.replace(/[^ll ]/g, "x"));
It seems to be interpreting the ll
as separate characters and not a character sequence.
How would I go about solving this with regex and using the replace
method?
Upvotes: 1
Views: 83
Reputation: 626689
Match and capture what you want to keep, match everything else to replace:
var myStr = "Hello World";
console.log(myStr.replace(/(ll| )|[\s\S]/g, (x,y) => y || "x"));
Before ES6+:
var myStr = "Hello World";
console.log(myStr.replace(/(ll| )|[\s\S]/g, function (x,y) {
return y || "x";
})
);
So, (ll| )|[\s\S]
matches and captures into Group 1 ll
or a space, or just matches any char with [\s\S]
(you may use [^]
(in any JS environment) or a .
with /s
modifier (in ECMAScript2018+ compatible environments)) and if Group 1 matches (y
in the above code), it is returned back. Else, replace with x
.
Upvotes: 1
Reputation: 784948
You may use this pure regex solution using look-arounds:
var str = 'Hello World';
var re = /(?<!l)l(?!l)|[^l ]/g;
var repl = str.replace(re, 'x');
console.log(repl);
//=> xxllx xxxxx
RegEx Details:
(?<!l)l(?!l)
: Match l
if it is not followed and preceded by another l
|
; OR[^l ]
: Match any character that is not l
and not a spaceUpvotes: 2