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');
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');
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)
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)