替换对象和数组中的元素?

时间:2018-06-21 19:25:04

标签: javascript

如果从对象y中提取,例如'JPY 20,USD 20',我想用扩展名DOLLAR和JEN代替USD和JPY的缩写。它必须看起来像这样: 'JPY 20,USD 20'替换为'JEN 20,DOLLAR 20'

var x = {
    'U': 'DOLLAR',
    'J': 'JEN',
    'E': 'EURO'
};


var  y = [
    'U 50',
    'J 20, U 20',
    'E 20, J 10'
];

var z = y[Math.floor(Math.random() * y.length)]; //example 'JPY 20, USD 20'

for(var key in x) {
    var c = new RegExp({key}, "g");
    z = z.replace(key, x[key]);  
    console.log(z);      //It should looks like //'JEN 20, DOLLAR 20'
}  

var x = { U: 'DOLLAR', J: 'JEN', E: 'EURO' },
    y = ['U 50', 'J 20, U 20', 'E 20, J 10'],
    z = y[Math.floor(Math.random() * y.length)],
    key,
    regex;

for (key in x) {
    regex = new RegExp(key, "g");
    z = z.replace(regex, x[key]);  
}  

console.log(z);

1 个答案:

答案 0 :(得分:0)

您可以替换所有字符串,然后将其与管道连接以进行替代搜索,并替换为新值。

var array = ['U 50', 'J 20, U 20', 'E 20, J 10'],
    replacements = { U: 'DOLLAR', J: 'JEN', E: 'EURO' },
    string = array[Math.floor(Math.random() * array.length)],
    regex = new RegExp(Object.keys(replacements).join('|'), "g");

string = string.replace(regex, key => replacements[key]);  

console.log(string);