Javascript (多个)用数组替换字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4848263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:24:04  来源:igfitidea点击:

(Multiple) Replace string with array

javascriptjqueryreplace

提问by Simasher

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:

有没有办法将这些 FIND 和 REPLACE 参数放入一个数组中,并一次替换所有这些参数?如:

reps = [["UN","Ali"], ["LC","Turkey"], ["AG","29"], ...]
$(str).replace(reps)

回答by kennytm

No jQuery is required.

不需要 jQuery。

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

return str.replace(/\[(\w+)\]/g, function(s, key) {
   return reps[key] || s;
});
  • The regex /\[(\w+)\]/gfinds all substrings of the form [XYZ].
  • Whenever such a pattern is found, the function in the 2nd parameter of .replacewill 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.)
  • 正则表达式/\[(\w+)\]/g查找形式为 的所有子字符串[XYZ]
  • 每当发现这样的模式时,将调用 的第二个参数中的函数.replace来获取替换。
  • 它将搜索关联数组并尝试在键存在 ( reps[key]) 时返回该替换。
  • 否则,s将返回原始子字符串 ( ),即不替换任何内容。(请参阅在 Javascript 中,当变量声明中存在逻辑运算符时,这意味着什么?有关如何||使其工作。)

回答by Sarfraz

You can do:

你可以做:

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

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