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?

TonyW
  • 18,375
  • 42
  • 110
  • 183
  • 1
    `new RegExp('\\s+'+word+'\\s+', 'g')`, or ``new RegExp(String.raw`\s+${word}\s+`, 'g')``. – Felix Kling Oct 16 '17 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. – worc Oct 16 '17 at 17:31

0 Answers0