0

I have the following sentence:

var sen = "helloadd but add sumis sum";

I need to replace add and sum in their whole string only, but not replace add in helloadd or sum in sumis.

So I did the following and it works:

sen = sen.replace(/\s+add\s+/g, "<b>$1</b>");

But I have the words to be replaced in an array: var words = [add, sum] and use the forEach way to replace each word appeared in the sentence:

words.forEach(function(word){
    // this does not work though
    sen = sen.replace(new RegExp(/\s+/ + word + /\s+/, 'g'), "<b>$1</b>");
});

Question here is to how to use variable together with space in the regex?

2
  • 1
    new RegExp('\\s+'+word+'\\s+', 'g'), or new RegExp(String.raw`\s+${word}\s+`, 'g'). Commented Oct 16, 2017 at 17:17
  • 1
    your comment doesn't work, btw. it won't match the last sum since it isn't followed by a whitespace. the duplicate link uses word boundary and seems to work just fine. Commented Oct 16, 2017 at 17:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.