不确定我是否可以在标题中更好地解释,但我会在这里更好地解释。我正在尝试创建一个充当简单“模板器”的函数。我给它提供了一个带有某些标签“{{name}}”的字符串,它会用某个字符串替换它。
这是我到目前为止所拥有的:
调用函数:
loadTemplate("<div>{{name}}, {{anotherString}}</div>", {
name: "Hunter",
anotherString: "is amazing!!!!"
});
功能:
// Created this to make my life easier :)
function loadTemplate(template, data) {
var tags = template.split("{{").pop().split("}}").shift();
console.log(tags); // This only gives me the last occurrence.
}
如何循环遍历字符串中所有出现的 {{variable}} 以便我可以将其替换为关联的数据?
类似于Handlebars.js
(我想要一个 super 轻量且快速的函数,而不是整个插件)
最佳答案
使用替换文本的回调,通过一个正则表达式替换可以很容易地做到这一点:
function loadTemplate(template, data) {
return template.replace(/\{\{(\w+)\}\}/g, function(match, key) {
return data[key];
});
}
alert(loadTemplate("<div>{{name}}, {{anotherString}}</div>", {
name: "Hunter",
anotherString: "is amazing!!!!"
}));
模式为 \{\{(\w+)\}\}
,意思是 {{
,后跟捕获的单词,后跟 }}
。单词是字母数字字符和下划线的任意序列。
如果您希望能够使用任何不包含的键值(例如,带有空格),您可以将 \w+
替换为 .+?
}}
:
function loadTemplate(template, data) {
return template.replace(/\{\{(.+?)\}\}/g, function(match, key) {
return data[key];
});
}
alert(loadTemplate("<div>{{The Name}}, {{Another $tring}}</div>", {
"The Name": "Hunter",
"Another $tring": "is amazing!!!!"
}));
关于javascript - 替换多次出现的动态字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30698764/