我有一个大字符串,需要更换几次。如
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
...
有没有办法将这些FIND和REPLACE参数放到一个数组中,并立即替换所有这些参数?如:
reps = [["UN","Ali"], ["LC","Turkey"], ["AG","29"], ...]
$(str).replace(reps)
答案 0 :(得分:26)
不需要jQuery。
var reps = {
UN: "Ali",
LC: "Turkey",
AG: "29",
...
};
return str.replace(/\[(\w+)\]/g, function(s, key) {
return reps[key] || s;
});
/\[(\w+)\]/g
查找[XYZ]
形式的所有子字符串。.replace
的第二个参数中的函数来获取替换。reps[key]
),它将搜索关联数组并尝试返回该替换。 s
),即不替换任何内容。 (有关||
如何使其发挥作用,请参阅In Javascript, what does it mean when there is a logical operator in a variable declaration?。)答案 1 :(得分:3)
你可以这样做:
var array = {"UN":"ALI", "LC":"Turkey", "AG":"29"};
for (var val in array) {
str = str.split(val).join(array[val]);
}