I am working on a function that receives an object organised in this manner: {"oldID1":"newID1", "oldID2":"newID2" , … }
This information is to be fed into another function which will perform a string replace of oldID1 with newID1, oldID2 with newID2 etc, inside a textarea containing these ID's.
This initial object originally comes from a series of sorting operations, such that the object keys represent a list's original order, and the object values represent the newly sorted order. So, for example, I would be confronted with an object looking like this:
{
"1":"3",
"2":"1",
"3":"2",
"4":"4"
}
Where the intent was to move item 3 to the top of the list. As a result, for the text in the separate textarea, 1 should be replaced by 3, 2 by 1 and 3 by 2.
When I try to iterate the object and perform the replace, I run into problems because some text gets replaced more than once. So '1' gets replaced by '3', but then later on gets replaced by '2'.
Here is the code I'm using to loop through that object:
$.each(the_object, function(key, value){
replace_text(key,value);
});
function replace_text(old_id, new_id){
var textarea = $("#the_textarea");
var str = textarea.val();
var replace_regex = new RegExp("<pic_"+old_id+">");
str = str.replace(replace_regex, '<pic_'+new_id+'>');
the_textarea.val(str);
}
I should emphasise that the sorting process is independent of the text replacing. I am simply concerned in finding the best way to perform that text replace given the object I have.
Thanks in advance