[使用几个先前的答案的组合,我试图将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回调的第二个参数:
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);