Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Multiple) Replace string with array [duplicate]

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)
like image 357
Simasher Avatar asked Nov 28 '22 10:11

Simasher


2 Answers

No jQuery is required.

var reps = {
  UN: "Ali",
  LC: "Turkey",
  AG: "29",
  ...
};

return str.replace(/\[(\w+)\]/g, function(s, key) {
   return reps[key] || s;
});
  • The regex /\[(\w+)\]/g finds all substrings of the form [XYZ].
  • Whenever such a pattern is found, the function in the 2nd parameter of .replace will be called to get the replacement.
  • It will search the associative array and try to return that replacement if the key exists (reps[key]).
  • Otherwise, the original substring (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.)
like image 116
kennytm Avatar answered Dec 13 '22 18:12

kennytm


You can do:

var array = {"UN":"ALI", "LC":"Turkey", "AG":"29"};

for (var val in array) {
  str = str.split(val).join(array[val]);
}
like image 38
Sarfraz Avatar answered Dec 13 '22 17:12

Sarfraz