4

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)
CRABOLO
  • 8,605
  • 39
  • 41
  • 68
Simasher
  • 117
  • 1
  • 3
  • 13

2 Answers2

26

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.)
Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 2
    +1, although: This assumes the replacement will never be an empty string. @user: If sometimes the replacements are empty strings, change the body of the function to `var rep = reps[key]; return typeof rep === "undefined" ? s : rep;` – T.J. Crowder Jan 31 '11 at 06:55
  • Just tried it in Chrome's console, it doesn't work. `var reps = { UN: "Ali", LC: "Turkey", AG: "29" };`, then `var str = "hello UN, I'm in LC, AG"`, and finally `str.replace(/\[(\w+)\]/g, function(s, key) { return reps[key] || s; });` returns the inital string, without any replacement. – DevonDahon Apr 02 '19 at 11:24
  • @maxagaz Please check OP's question, the `str` is `var str = "Username:[UN] Location:[LC] Age:[AG]"`. There are brackets around the UN, LC and AG. – kennytm Apr 02 '19 at 18:24
4

You can do:

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

for (var val in array) {
  str = str.split(val).join(array[val]);
}
Sarfraz
  • 377,238
  • 77
  • 533
  • 578