0

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?

3
  • Use new RegExp (terms.join('|'), 'gim'). Interpolation does not work in a regex literal. Commented Aug 15, 2020 at 11:45
  • RegExp constructor takes a string, there's no need for passing a string to the constructor wrapped within //. Commented Aug 15, 2020 at 11:48
  • can your input array elements have regex metacharacters? if so, you'll have to escape them if you want to match them literally... plus you also have to take care of alternation order if terms start with same substring like par and park, see my tutorial for examples Commented Aug 15, 2020 at 13:21

1 Answer 1

1

Your argument to the RegExp contructor is wrong. Just pass in the string. Like so:

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.