How to replace multiple strings with multiple other strings in Javascript?
Question
I have a string called I have cats, dogs, and goats.
, and I want to replace to I have AA, BB, and CC.
.
How to make it happen only with one function?
Answer
If you only wanna it happen easily, just need one function to replace all of them.1
2
3
4
5
6
7
8
9var str = "I have cats, dogs, and goats";
var mapObj = {
cats:"AA",
dogs:"BB",
goats:"CC"
};
str = str.replace(/cat|dog|goat/gi, function(matched){
return mapObj[matched];
});
Reference
This is the end of post