I have a large string which need be replaced a few times. Such as
var str="Username:[UN] Location:[LC] Age:[AG] ... "
str=str.replace("[UN]","Ali")
str=str.replace("[LC]","Turkey")
str=str.replace("[AG]","29")
...
//lots of replace
...
Is there a way to put those FIND and REPLACE parameters to an array, and replace all of them at once? Such as:
reps = [["UN","Ali"], ["LC","Turkey"], ["AG","29"], ...]
$(str).replace(reps)
                No jQuery is required.
var reps = {
  UN: "Ali",
  LC: "Turkey",
  AG: "29",
  ...
};
return str.replace(/\[(\w+)\]/g, function(s, key) {
   return reps[key] || s;
});
/\[(\w+)\]/g finds all substrings of the form [XYZ]..replace will be called to get the replacement.reps[key]). s) will be returned, i.e. nothing is replaced. (See In Javascript, what does it mean when there is a logical operator in a variable declaration? for how || makes this work.)You can do:
var array = {"UN":"ALI", "LC":"Turkey", "AG":"29"};
for (var val in array) {
  str = str.split(val).join(array[val]);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With