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 ha
I expanded on @BenMcCormicks a bit. His worked for regular strings but not if I had escaped characters or wildcards. Here's what I did
str = "[curl] 6: blah blah 234433 blah blah";
mapObj = {'\\[curl] *': '', '\\d: *': ''};
function replaceAll (str, mapObj) {
var arr = Object.keys(mapObj),
re;
$.each(arr, function (key, value) {
re = new RegExp(value, "g");
str = str.replace(re, function (matched) {
return mapObj[value];
});
});
return str;
}
replaceAll(str, mapObj)
returns "blah blah 234433 blah blah"
This way it will match the key in the mapObj and not the matched word'
<!DOCTYPE html>
<html>
<body>
<p id="demo">Mr Blue
has a blue house and a blue car.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/\n| |car/gi, function myFunction(x){
if(x=='\n'){return x='<br>';}
if(x==' '){return x=' ';}
if(x=='car'){return x='BMW'}
else{return x;}//must need
});
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
You can use a function to replace each one.
var str = "I have a cat, a dog, and a goat.";
var mapObj = {
cat:"dog",
dog:"goat",
goat:"cat"
};
str = str.replace(/cat|dog|goat/gi, function(matched){
return mapObj[matched];
});
jsfiddle example
If you want to dynamically maintain the regex and just add future exchanges to the map, you can do this
new RegExp(Object.keys(mapObj).join("|"),"gi");
to generate the regex. So then it would look like this
var mapObj = {cat:"dog",dog:"goat",goat:"cat"};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.replace(re, function(matched){
return mapObj[matched];
});
And to add or change any more replacements you could just edit the map.
fiddle with dynamic regex
If you want this to be a general pattern you could pull this out to a function like this
function replaceAll(str,mapObj){
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
return str.replace(re, function(matched){
return mapObj[matched.toLowerCase()];
});
}
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.
Use numbered items to prevent replacing again. eg
let str = "I have a %1, a %2, and a %3";
let pets = ["dog","cat", "goat"];
then
str.replace(/%(\d+)/g, (_, n) => pets[+n-1])
How it works:- %\d+ finds the numbers which come after a %. The brackets capture the number.
This number (as a string) is the 2nd parameter, n, to the lambda function.
The +n-1 converts the string to the number then 1 is subtracted to index the pets array.
The %number is then replaced with the string at the array index.
The /g causes the lambda function to be called repeatedly with each number which is then replaced with a string from the array.
In modern JavaScript:-
replace_n=(str,...ns)=>str.replace(/%(\d+)/g,(_,n)=>ns[n-1])
This worked for me:
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
function replaceAll(str, map){
for(key in map){
str = str.replaceAll(key, map[key]);
}
return str;
}
//testing...
var str = "bat, ball, cat";
var map = {
'bat' : 'foo',
'ball' : 'boo',
'cat' : 'bar'
};
var new = replaceAll(str, map);
//result: "foo, boo, bar"
With my replace-once package, you could do the following:
const replaceOnce = require('replace-once')
var str = 'I have a cat, a dog, and a goat.'
var find = ['cat', 'dog', 'goat']
var replace = ['dog', 'goat', 'cat']
replaceOnce(str, find, replace, 'gi')
//=> 'I have a dog, a goat, and a cat.'