javascript - 替换多次出现的动态字符串?

标签 javascript jquery regex performance

不确定我是否可以在标题中更好地解释,但我会在这里更好地解释。我正在尝试创建一个充当简单“模板器”的函数。我给它提供了一个带有某些标签“{{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/

相关文章:

javascript - 自定义帖子类型 - 类别添加按钮不起作用

jquery - 在 jQuery 不起作用的情况下使用加号和减号增加数量

javascript - jquery动画从一个 Angular 向内

python re 模块替换文本文件中的二进制数据?

python - 如何在python中排除字符组

javascript - IE 8 在 "slow"jQuery 脚本上提示用户

javascript - 如何将数组值添加到对象

javascript - best_in_place nil 和 edit 函数不能在 rails4 上使用 bootstrap 应用程序

regex - 是否存在一种算法来确定关于特定XSD架构的所有有效XML实例的集合是否为常规语言?

javascript - 使用 ES6 创建 HTML 元素