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,82439 gold badges46 silver badges68 bronze badges
asked Jan 31, 2011 at 6:41
-
@KrzysztofSafjanowski it should be the other way around since this one is older than your duplicate proposalNicolas Filotto– Nicolas Filotto2016年11月03日 11:38:13 +00:00Commented Nov 3, 2016 at 11:38
2 Answers 2
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.)
answered Jan 31, 2011 at 6:45
Sign up to request clarification or add additional context in comments.
3 Comments
T.J. Crowder
+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;
DevonDahon
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.kennytm
@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.You can do:
var array = {"UN":"ALI", "LC":"Turkey", "AG":"29"};
for (var val in array) {
str = str.split(val).join(array[val]);
}
answered Jan 31, 2011 at 6:46
Comments
lang-js