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

时间:2022-07-05 16:52:57

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,'*');

This result will be :

结果将是:

st1ck2v3rfl2w

I want to use regex at the same time. How can I do that ? Thank you.

我想同时使用正则表达式。我怎样才能做到这一点 ?谢谢。

2 个解决方案

#1


10  

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

检查小提琴

#2


5  

One possible solution:

一种可能的方案:

var a = ['a','o','e'],
    b = ['1','2','3'];

'*'.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的评论,这是另一个更加万无一失的解决方案:

'*'.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 compatibility for indexOf method and use polyfill if required.

N.B。:检查indexOf方法的浏览器兼容性,并根据需要使用polyfill。

#1


10  

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

检查小提琴

#2


5  

One possible solution:

一种可能的方案:

var a = ['a','o','e'],
    b = ['1','2','3'];

'*'.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的评论,这是另一个更加万无一失的解决方案:

'*'.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 compatibility for indexOf method and use polyfill if required.

N.B。:检查indexOf方法的浏览器兼容性,并根据需要使用polyfill。