- I have modified Ben McCormick's answer to work with your new test case.
- I simply added word boundaries to the regular expression:
/\b(cat|dog|goatcathy|cat|catch)\b/gi
"Run code snippet" to see the results below:
var str = "I have a cat, a dogcatch, and a goatcathy.";
var mapObj = {
catcathy:"dog""cat",
dogcat:"goat""catch",
goatcatch:"cat""cathy"
};
str = str.replace(/\b(cat|dog|goatcathy|cat|catch)\b/gi, function(matched){
return mapObj[matched];
});
console.log(str);