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?