(Multiple) Replace string with array

I have a large string that needs to be replaced several times. For instance,

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 set FIND and REPLACE parameters to an array and replace them immediately? For instance:

 reps = [["UN","Ali"], ["LC","Turkey"], ["AG","29"], ...] $(str).replace(reps) 
+4
source share
2 answers

No jQuery.

 var reps = { UN: "Ali", LC: "Turkey", AG: "29", ... }; return str.replace(/\[(\w+)\]/g, function(s, key) { return reps[key] || s; }); 
  • The regular expression /\[(\w+)\]/g finds all substrings of the form [XYZ] .
  • Whenever such a template is found, the function for the second parameter .replace will be called to get a replacement.
  • It will look for an associative array and try to return this replacement if the key exists ( reps[key] ).
  • Otherwise, the original substring ( s ) will be returned, i.e. nothing will be replaced. (See in Javascript what this means when there is a logical operator in a variable declaration? How || does this work.)
+25
source

You can do:

 var array = {"UN":"ALI", "LC":"Turkey", "AG":"29"}; for (var val in array) { str = str.split(val).join(array[val]); } 
+3
source

Source: https://habr.com/ru/post/1337727/


All Articles