Here I have more than 30 words that wish to replace, how can I improve the efficiency and no need to write more than 30 replace
?
"sample string".split(" ").map((x) => {
return x
.replace(/bmanb/g, "manchester")
.replace("/butdb/g", "united")...(still have 30 words to go)
})
3
Answers
You could do that dynamically with a lookup matrix that stores all your replacements.
If you are only replacing words, i.e. using the
b
boundary before and after the regex and no non-alphanumeric character to match, then use a look-up object, whose keys are the words you want to replace. One generic regex could even suffice: