Specific Solution(具体解决方案)
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
(jsfiddle示例)
Generalizing it(概括它)
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
(摆弄动态正则表达式)
Making it Reusable(使其可重用)
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.
(因此,您只需将str和所需替换的映射传递给函数,它将返回转换后的字符串。)
fiddle with function
(摆弄功能)
To ensure Object.keys works in older browsers, add a polyfill eg from MDN or Es5 .
(为了确保Object.keys在较旧的浏览器中可以正常工作,请添加一个polyfill例如从MDN或Es5 。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…