Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I was wondering if anyone could help me with a simple solution to convert each integer in a javascript string to its corresponding key in a key:value pair array. 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'

Sorry this is my first post so I hope that makes sense, I'm using javascript and jquery (latest version). Any help would be grealy appreciated.

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

I'm just doing this off the top of my head, but this should work.

var new_str = str;

for (var key in arr) {
    if (!arr.hasOwnProperty(key)) {
        continue;
    }

    new_str = new_str.replace(key, arr[key]);
}

If you wanted all occurrences of the number to be replaced, you'd need to incorporate a Regex into the mix:

var new_str = str;

for (var key in arr) {
    if (!arr.hasOwnProperty(key)) {
        continue;
    }

    new_str = new_str.replace(new RegExp(key, "g"), arr[key]);
}

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 use for-in loops on objects, not arrays, because of issues with prototype leakage and others.

You can also do this with jQuery, but it's probably overkill:

var new_str = str;

$.each(arr, function (key, value) {
    new_str = new_str.replace(key, value);
});
share|improve this answer
 
Sorry for the usage of the variable names was trying to use a simple example. I continue to get a typeerror though when trying to use the replace method, do I need to type cast the key or something similar? –  Ninja Pants Jun 26 '12 at 1:55
 
Forget that, I worked it out. Thank you very much for your help and prompt response. Quick question, why is the jquery version overkill? –  Ninja Pants Jun 26 '12 at 2:17
 
Because there is nothing in jQuery to help with the solution. –  RobG Jun 26 '12 at 3:12
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.