简体   繁体   English

用Javascript中的正则表达式一次替换多个字符串

[英]Replace Multiple String at Once With Regex in Javascript

I tried this : Replace multiple strings at once And this : javascript replace globally with array how 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.谢谢。

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];
});

Check fiddle检查小提琴

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)];
});

NB: Check the browser compatibility for indexOf method and use polyfill if required.注意:检查indexOf方法的浏览器兼容性,并在需要时使用polyfill

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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM