使用RegEx替换字符串中的所有变量

问题描述 投票:0回答:1

[使用几个先前的答案的组合,我试图将RegEx放在一起,使我可以替换所有花括号中出现的所有内容

我到现在为止,但是似乎没有用

var str = "The {type} went to the {place}";


var mapObj = {
   type: 'Man',
   place: "Shop"

};
var re = new RegExp(/(?<=\{)Object.keys(mapObj).join("|")(?=\})/, "gim");
str = str.replace(re, function(matched){
  return mapObj[matched.toLowerCase()];
});

console.log(str);

我在上一个答案中添加了(?<= {)和(?=}),使其仅与键在花括号内的匹配项匹配

上一个答案-Replace multiple strings with multiple other strings

javascript regex
1个回答
3
投票

使用捕获组,您将获得该值作为replace回调的第二个参数:

var str = "The {type} went to the {place}";

var mapObj = {
  type: 'Man',
  place: "Shop"

};

str = str.replace(/\{([^{}]+)\}/gim, function(_, c) {
  return mapObj[c.toLowerCase()] || `{${c}}`;
});

console.log(str);
© www.soinside.com 2019 - 2024. All rights reserved.