join - Javascript - Replace only if there is a perfect match -


i studying javascript , stumbled upon problem. there way can specify replace words if there perfect match? thank in advance.

ps: thought 'g' fix problem did half-way.

var text = "isabella moving new york in march";  var words = ["is","in"];  var combine = new regexp(words.join("|"),"g");    text = text.replace(combine,"replace");  console.log(text);

you can wrap joined words in group (preferably non-capturing) , surround groub word boundaries \b regexp this:

/\b(?:word1|word2|...|wordn)\b/g 

change:

var combine = new regexp("\\b(?:" + words.join("|") + ")\\b", "g"); //                       ^^^^^^^^^^^               ^^^^^^^^^ 

example:

var text = "isabella moving new york in march";  var words = ["is","in"];  var combine = new regexp("\\b(?:" + words.join("|") + ")\\b","g");    text = text.replace(combine," replace ");  console.log(text);

note: g modifier mean global (mean replace not first matches)


Comments