结合使用之前的几个答案,我尝试组合一个正则表达式,它允许我替换大括号内出现的所有内容
我已经做到了这一点,但似乎不起作用
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
最佳答案
使用捕获组,您将获得作为替换回调的第二个参数的值:
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);
关于javascript - 使用正则表达式替换字符串中的所有变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59583204/