使用数组元素替换多个occurence串 [英] Replace multiple occurence string using array element

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

问题描述

我在一个关联数组几个字符串:

I have several strings in an associative array:

    var arr = {
        '============================================': '---------',
        '++++++++++++++++++++++++++++++++++++++++++++': '---------',
        '--------------------------------------------': '---------'
    };

我要替换相应的值每个键的出现。我想出来的是:

I want to replace occurrences of each key with the corresponding value. What I've come up with is:

    for (var i in arr)
    {
        strX = str.replace(i, arr[i]);

        console.log('arr[\''+i+'\'] is ' + arr[i] + ': ' + strX);
    }

这工作,但只在第一次出现。如果我改变了正则表达式 / I / G 中,code不起作用。

This works, but only on first occurence. If I change the regex to /i/g, the code doesn't work.

for (var i in arr)
{
    strX = str.replace(/i/g, arr[i]);

    console.log('arr[\''+i+'\'] is ' + arr[i] + ': ' + strX);
}

你们是否知道如何解决此问题?

Do you guys know how to work around this?

推荐答案

而不是

strX = str.replace(/i/g, arr[i]);

您想要做这样的事情。

strX = str.replace(new RegExp(i, "g"), arr[i]);

这是因为 / I / G 指的是字母i,变量不是i的值您的基本字符串的一个有加号,这是正则表达式元字符。这些都被转义。最快的黑客如下:

This is because /i/g refers to the letter i, not the value of variable i. HOWEVER one of your base string has plus signs, which is a metacharacter in regexes. These have to be escaped. The quickest hack is as follows:

new RegExp(i.replace(/\+/g, "\\+"), "g"), arr[i]);

下面是一个工作的例子: http://jsfiddle.net/mFj2f/

Here is a working example: http://jsfiddle.net/mFj2f/

在一般情况下,虽然,你应该检查所有的元字符,我想。

In general, though, one should check for all the metacharacters, I think.

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

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