Reputation: 123
I'm trying to replace all "WUB" in a string with a blank space. The problem is, if I have 2 "WUB" in a row, it will return 2 blank spaces. How do only return 1 blank space if I have "WUBWUB"?
function songDecoder(song) {
var replacedLyrics = song.replace(/#|WUB/g,' ');
return replacedLyrics;
}
Upvotes: 0
Views: 424
Reputation: 5753
/#|WUB/g
should be /#|(WUB)+/g
for your purpose. Do you also want to replace multiple "#"s with a single space. Then you might want /(#|WUB)+/g
The parentheses group the target strings together, then plus seeks one or more repetition of the group.
If you don't want a space at the beginning or end of your string, that could be another regex function, but probably the most straightforward method is to use the .trim() function. So:
alert(
songDecoder('WUBYOUREWUBWELCOMEWUB')
)
function songDecoder(song) {
var replacedLyrics = song.replace(/(#|WUB)+/g,' ').trim();
return replacedLyrics;
}
Upvotes: 0
Reputation: 15247
Try this regex /(WUB)+/g
it will match 1 or more element in the parenthesis
function songDecoder(song)
{
var replacedLyrics = song.replace(/(WUB)+/g,' ');
return (replacedLyrics);
}
console.log(songDecoder("hello world !"));
console.log(songDecoder("WUB"));
console.log(songDecoder("helloWUBWUBworldWUB!"));
Upvotes: 3
Reputation: 3676
Change your code to .replace(/#|(WUB)+/g, " ");
.
This searches for as many "WUB's" in a row before replacing them with a blank space
Upvotes: 0