英文:
Replace all variables in string using 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);
英文:
Using a combination of a couple of previous answers I've tried to put together a RegEx that'll allow me to replace all occurrences of anything within curly braces
I got this far, but it doesn't seem to work
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);
I added (?<={) and (?=}) to the previous answer to have it only match occurrences where the key was within curly braces
Previous Answer - https://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings
答案1
得分: 3
使用捕获组,您将在替换回调的第二个参数中获取该值:
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);
英文:
Use a capture group, and you'll get the value as the 2nd param of the replace callback:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论