I’m trying to convert each integer in a string to its corresponding value in an object based on its key–value entries. For example if I have:
var arr = {
"3": "value_three",
"6": "value_six",
"234": "other_value"
};
var str = "I want value 3 here and value 234 here";
I would expext the output to be:
new_str = "I want value_three here and value other_value here"
I’m just doing this off the top of my head, but this should work.
If you wanted all occurrences of the number to be replaced, you’d need to incorporate a Regex into the mix:
Also, I’d pick another name other than
arr, as that implies it’s an array when it’s clearly an object. Also, make sure you only usefor-inloops on objects, not arrays, because of issues with prototype leakage and others.You can also do this with jQuery, but it’s probably overkill: