I am currently studying javascript and I stumbled upon this problem. Is there a way I can specify to replace the words only if there is a perfect match?
PS: I thought that 'g' will fix the problem but it only did it half-way.
var text = "Isabella is moving to 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 the joined words in a group (preferably non-capturing) and then surround the groub with word boundaries \b so the regexp will look like this:
/\b(?:word1|word2|...|wordn)\b/g
Change:
var combine = new RegExp("\\b(?:" + words.join("|") + ")\\b", "g");
// ^^^^^^^^^^^ ^^^^^^^^^
Example:
var text = "Isabella is moving to 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: the g modifier mean global (mean replace not only the first but all matches)
Only put spaces in words :)
var text = "Isabella is moving to New York in March";
var words = [" is "," in "];
var combine = new RegExp(words.join("|"),"g");
text = text.replace(combine," REPLACE ");
console.log(text);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With