1

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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

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"
just take the same code. the lenght of the replacement strings is not importent unless they are unique.
console.log return JEURON instead JEN

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.