0

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;
}
Yura
  • 2,925
  • 2
  • 18
  • 27
Marvin
  • 103
  • 1
  • 8
  • Possible duplicate of [Replace multiple whitespaces with single whitespace in JavaScript string](https://stackoverflow.com/questions/6163169/replace-multiple-whitespaces-with-single-whitespace-in-javascript-string) – Steve Oct 31 '18 at 18:43
  • @SteveNosse, that question addresses a string that already has multiple whitespaces in it. This question seeks to prevent such an occurrence in the first place. – pwilcox Nov 01 '18 at 20:18

3 Answers3

3

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!"));
Cid
  • 14,968
  • 4
  • 30
  • 45
0

/#|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;
}
pwilcox
  • 5,542
  • 1
  • 19
  • 31
  • worked like a charm! but let say you don't want a space at the beginning or at the end for example "WUBTHANKWUBYOUWUB" to extract "THANK YOU" – Marvin Oct 31 '18 at 15:12
  • Of course @marinafive. Consider marking as an answer! – pwilcox Oct 31 '18 at 15:36
0

Change your code to .replace(/#|(WUB)+/g, " ");.

This searches for as many "WUB's" in a row before replacing them with a blank space

T. Dirks
  • 3,566
  • 1
  • 19
  • 34