If I draw from the object y, for example 'JPY 20, USD 20', I want to replace the USD and JPY abbreviation with the extended name DOLLAR and JEN. It has to look like this: 'JPY 20, USD 20' replace to '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);
asked Jun 21, 2018 at 19:25
Umbro
2,22413 gold badges48 silver badges108 bronze badges
1 Answer 1
You coudl take all strings for replacement and join it with pipe for aleternative searches and replace with the new value.
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);
answered Jun 21, 2018 at 19:29
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Umbro
How should I set regex if var x = { U: 'DOLLAR', J: 'JEN', E: 'EURO' }, y = ['U 50', 'J 20, U 20', 'E 20, J 10']; Random 'J 20, U 20'; console.log return "EURO 20, JEURON 10"
Nina Scholz
just take the same code. the lenght of the replacement strings is not importent unless they are unique.
Umbro
console.log return JEURON instead JEN
lang-js