Suppose I have an array with a few elements and also a string with a sentence.
I need a regex that would detect all the occurrences of all the array items in the string and replace them.
So far I came up with something like this:
let terms = ['apple','orange','banana juice']
let t = "Apples and oranges are much better than banana juice and can be eaten separately. I like apples more though."
let regexp = new RegExp (/ + terms.join('|') + /, 'gim')
t = t.replace(regexp, 'N/A')
console.log(t)
But it does not do any replacement even though my regex is supposed to be
/orange|apple|banana juice/
How can I fix that?
I also want to make sure that if one of the array elements has a special character — is there a way to ensure that it doesn't break the RegExp or when I simply use a variable in replace it's all going to work out fine?
new RegExp (terms.join('|'), 'gim'). Interpolation does not work in a regex literal.RegExpconstructor takes a string, there's no need for passing a string to the constructor wrapped within//.parandpark, see my tutorial for examples