Reputation: 1813
If I have this string: foo bar baz qux bar quux quuz
, I would like to replace each character of bar
by X
(foo XXX baz qux XXX quux quuz
).
Maybe .replace()
can be used in such a way? Obviously a "foo bar baz qux bar quux quuz".replace(/bar/g, "X")
wouldn't be enough since it would return foo X baz qux X quux quuz
instead of foo XXX baz qux XXX quux quuz
.
This is just an example, but I need to use regex. I can't do something like this:
"foo bar baz qux bar quux quuz"
.split(" ")
.map(x => x === "bar" ? "X".repeat(x.length) : x)
.join(" ")
I need the bar
to be found by a regex.
Upvotes: 0
Views: 38
Reputation: 35482
You can use a function to generate the replacement:
"foo bar baz qux bar quux quuz".replace(/bar/g, m => "X".repeat(m.length))
Upvotes: 1