javascript用数组替换全局 [英] javascript replace globally with array

查看:171
本文介绍了javascript用数组替换全局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用数组进行替换:

You can use array for replacement:

var array = {"from1":"to1", "from2":"to2"}

for (var val in array)
    text = text.replace(array, array[val]);

但是如果你需要全局替换,即
text = text.replace(/ from / g,to);

But what if you need to replace globally, ie text = text.replace(/from/g, "to");

数组相当大,所以如果我写text = text.replace(...),脚本会占用大量空间)对于每个变量。

Array is pretty big, so script will take a lot of space if I write "text = text.replace(...)" for every variable.

在这种情况下如何使用数组?
/ from1 / g:to1不起作用。

How can you use array in that case? "/from1/g":"to1" does not working.

推荐答案

var array = {"from1":"to1", "from2":"to2"}

for (var val in array)
    text = text.replace(new RegExp(val, "g"), array[val]);

编辑:正如Andy所说,你可能不得不使用像这一个

As Andy said, you may have to escape the special characters using a script like this one.

这篇关于javascript用数组替换全局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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