I'm trying to replace multiple words in a string with multiple other words. The string is "I have a cat, a dog, and a goat."
However, this does not produce "I have a dog, a goat, and a cat", but instead it produces "I have a cat, a cat, and a cat". Is it possible to replace multiple strings with multiple other strings at the same time in JavaScript, so that the correct result will be produced?
var str = "I have a cat, a dog, and a goat.";
str = str.replace(/cat/gi, "dog");
str = str.replace(/dog/gi, "goat");
str = str.replace(/goat/gi, "cat");
//this produces "I have a cat, a cat, and a cat"
//but I wanted to produce the string "I have a dog, a goat, and a cat".
/* replaceSome method for strings it takes as ,much arguments as we want and replaces all of them with the last argument we specified 2013 CopyRights saved for: Max Ahmed this is an example:
*/
jsFiddle: http://jsfiddle.net/CPj89/
With my replace-once package, you could do the following:
Using Jquery Replace multiple strings with multiple other strings
I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which allows you to do the following
which will replace the {0} and {1} with the array items and return the following string
or you could replace placeholders with object keys and values like so:
Specific Solution
You can use a function to replace each one.
jsfiddle example
Generalizing it
If you want to dynamically maintain the regex and just add future exchanges to the map, you can do this
to generate the regex. So then it would look like this
And to add or change any more replacements you could just edit the map.
fiddle with dynamic regex
Making it Reusable
If you want this to be a general pattern you could pull this out to a function like this
So then you could just pass the str and a map of the replacements you want to the function and it would return the transformed string.
fiddle with function
To ensure Object.keys works in older browsers, add a polyfill eg from MDN or Es5.
Just in case someone is wondering why the original poster's solution is not working: