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

查看:22
本文介绍了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]);

正如安迪所说,您可能必须使用像 this 这样的脚本来转义特殊字符一个.

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

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

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