javascript 用Javascript中的正则表达式一次替换多个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20743683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace Multiple String at Once With Regex in Javascript
提问by Ayro
I tried this : Replace multiple strings at onceAnd this : javascript replace globally with arrayhow ever they are not working.
我试过这个:一次替换多个字符串而这个:javascript 用数组全局替换它们如何不工作。
Can I do similar to this (its PHP):
我可以这样做吗(它的 PHP):
$a = array('a','o','e');
$b = array('1','2','3');
str_replace($a,$b,'stackoverflow');
This result will be :
这个结果将是:
st1ck2v3rfl2w
I want to use regex at the same time. How can I do that ? Thank you.
我想同时使用正则表达式。我怎样才能做到这一点 ?谢谢你。
回答by Just code
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];
});
回答by VisioN
One possible solution:
一种可能的解决方案:
var a = ['a','o','e'],
b = ['1','2','3'];
'stackoverflow'.replace(new RegExp(a.join('|'), 'g'), function(c) {
return b[a.indexOf(c)];
});
As per the comment from @Stephen M. Harris, here is another more fool-proof solution:
根据@Stephen M. Harris的评论,这是另一个更简单的解决方案:
'stackoverflow'.replace(new RegExp(a.map(function(x) {
return x.replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&');
}).join('|'), 'g'), function(c) {
return b[a.indexOf(c)];
});
N.B.:Check the browser compatibilityfor indexOf
method and use polyfillif required.
回答by Naresh Kumar
You can use delimiters and replace a part of the string
您可以使用分隔符并替换字符串的一部分
var obj = {
'firstname': 'John',
'lastname': 'Doe'
}
var text = "My firstname is {firstname} and my lastname is {lastname}"
console.log(mutliStringReplace(obj,text))
function mutliStringReplace(object, string) {
var val = string
var entries = Object.entries(object);
entries.filter((para)=> {
var find = '{' + para[0] + '}'
var regExp = new RegExp(find,'g')
val = val.replace(regExp, para[1])
})
return val;
}