Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Replace only if there is a perfect match

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);
like image 858
George Smith Avatar asked Dec 17 '25 21:12

George Smith


2 Answers

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)

like image 94
ibrahim mahrir Avatar answered Dec 20 '25 10:12

ibrahim mahrir


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);
like image 32
Christian Carrillo Avatar answered Dec 20 '25 12:12

Christian Carrillo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!