Reputation: 8471
What is the simplest way in JS to replace multiple things in string at once (without them interfering)? Like
"tar pit".replaceArray(['tar', 'pit'], ['capitol', 'house']);
...so it produces "capitol house", not "cahouseol house"?
Upvotes: 4
Views: 709
Reputation: 3170
how about this -
function replaceArray(text, toBeReplacedArray, replacementArray) {
for (var i = 0; i < toBeReplacedArray.length; i++) {
var re = new RegExp(toBeReplacedArray[i], 'g');
text = text.replace(re, '__' + i + '__');
}
for (var i = 0; i < replacementArray.length; i++) {
var re = new RegExp('__' + i + '__', 'g');
text = text.replace(re, replacementArray[i]);
}
return text;
}
replaceArray("tar pit", ['tar', 'pit'], ['capitol', 'house']);
Upvotes: 2
Reputation: 45121
var replaceArray = function(str, from, to) {
var obj = {}, regex;
from.forEach(function(item, idx){obj[item] = to[idx];});
regex = new RegExp('(' + from.join('|') + ')', 'g');
return str.replace(regex, function(match){return obj[match]});
}
replaceArray("tar pit", ["tar", "pit"], ["capitol", "house"]);
Upvotes: 6