使用Javascript中的Regex一次替换多个字符串 [英] Replace Multiple String at Once With Regex in Javascript

查看:35
本文介绍了使用Javascript中的Regex一次替换多个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过:一次替换多个字符串而且: javascript用array全局替换它们是如何工作的.

I tried this : Replace multiple strings at once And this : javascript replace globally with array how ever they are not working.

我可以这样做吗(它的PHP):

Can I do similar to this (its PHP):

$a = array('a','o','e');
$b = array('1','2','3');
str_replace($a,$b,'stackoverflow');

结果将是:

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

检查小提琴

这篇关于使用Javascript中的Regex一次替换多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆