2011-01-31 205 views
4

我有一個需要被替換幾次的大字符串。如(多個)用數組替換字符串

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

@KrzysztofSafjanowski應該反過來,因爲這是一個比你重複的提案 – 2016-11-03 11:38:13

回答

25

不需要jQuery。

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

return str.replace(/\[(\w+)\]/g, function(s, key) { 
    return reps[key] || s; 
}); 
+2

+1年紀大了,雖然:這假設替換不會是空字符串。 @user:如果有時替換爲空字符串,則將函數體改爲`var rep = reps [key]; return typeof rep ===「undefined」? s:rep;` – 2011-01-31 06:55:55

3

你可以這樣做:

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

for (var val in array) { 
    str = str.split(val).join(array[val]); 
}