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,540
  • 4
  • 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
  • 32,084
  • 8
  • 49
  • 92
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
  • 35,187
  • 4
  • 31
  • 54