0

Does anyone know if there a more effective way to replace multiple words with a single word, than this:

variableName.replace(/\small/g , 'word').replace(/\medium/g , 'word').replace(/\large/g , 'word').replace(/\x_large/g , 'word');
ccdavies
  • 1,576
  • 5
  • 19
  • 29

2 Answers2

1

Yes - modify your pattern to accept multiple options.

variableName.replace(/\b(word1|word2|word3)\b/g, 'word');

Also important to use word boundaries (\b) to ensure you match the words by themselves, not as part of other words (e.g. bridge vs. abridged)

Mitya
  • 33,629
  • 9
  • 60
  • 107
0

You can simply use alternation |

let str = 'w1 hello w2 how are you w3'

let op = str.replace(/\bw1|w2|w3\b/g, '')

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60