我正在开发一些函数,该函数用给定对象的对应值替换出现在与键匹配的方括号内的字符串,但是我不知道如何仅替换方括号内的那些字符串,它将取代所有内容,感谢您的帮助:
这是我到目前为止尝试过的:
function template(str, obj){
let new_str = str;
for (let key in obj)
{
new_str = new_str.replace(new RegExp(key, 'g'), obj[key]);
}
console.log(new_str);
}
template("Hi [name], your balance is [balance]", { name: "Joe", balance: 1200 });
我得到了:
"Hi [Joe], your 1200 is [12000]"
但是我希望:
"Hi Joe, your balance is 12000"
答案 0 :(得分:0)
由于键括在方括号中,因此您也必须将其放入样式中:
function template(str, obj) {
let new_str = str;
for (let key in obj) {
new_str = new_str.replace(new RegExp('\\[' + key + '\\]', 'g'), obj[key]);
}
console.log(new_str);
}
template("Hi [name], your balance is [balance]", {
name: "Joe",
balance: 1200
});
您还可以考虑使用带有替换功能的单个正则表达式来简化代码:
const template = (str, obj) => str.replace(
/\[([^\]]*)\]/g,
(match, possibleKey) => obj[possibleKey] ? obj[possibleKey] : match
);
console.log(template("Hi [name], your balance is [balance]", {
name: "Joe",
balance: 1200
}));
如果方括号中包含的内容始终存在于对象中,则不需要条件运算符:
const template = (str, obj) => str.replace(
/\[([^\]]*)\]/g,
(_, key) => obj[key]
);
console.log(template("Hi [name], your balance is [balance]", {
name: "Joe",
balance: 1200
}));
答案 1 :(得分:0)
您还需要匹配[]
。使用模板文字并将密钥包装在RegExp
中的function template(str, obj){
let new_str = str;
for (let key in obj)
{
new_str = new_str.replace(new RegExp(`\\[${key}\\]`, 'g'), obj[key]);
}
console.log(new_str);
}
template("Hi [name], your balance is [balance]", { name: "Joe", balance: 1200 });
{{1}}