/*
* 正则替换%s
* @para arg1(text) 需要替换的模版
* @para arg2 替换第一处%s
* @para arg3 替换第二处%s
* 返回替换后的字符串
*/
var sprintf = function (text) {
var i = ,
args = arguments,
len = args.length;
return text.replace(/%s/g, function () {
return (i < len) ? args[i++] : "";
});
};
/**
// 文档
<ul id="my-list">
<li><a href="#">hello world</a></li>
</ul>
// 模版 type="text/template" 服务器不会解析的mime类型
<script type="text/template" id="list-item">
<li><a href="%s">%s</a></li>
</script>
**/
// 添加一个模版节点
var addItem = function (url, text) {
var _script = document.getElementById("list-item"),
template = _script.text,
result = sprintf(template, url, text),
ele = document.getElementById("my-list"),
div = document.createElement("div");
// 正则替换后div.firstChild就是Node节点
div.innerHTML = result.replace(/^\s*/, "");
ele.appendChild(div.firstChild);
};
addItem("www.google.com/", "google");
一种更好的方式
(function(){
var regexp = /(?:\{\{)([a-zA-z][^\s\}]+)(?:\}\})/g;
function render(template, data) {
return template.replace(regexp, function(fullMatch, capture) {
if(data[capture]) {
return data[capture];
} else {
return fullMatch;
}
});
}
window.renderTemplate = render;
})();
var template = '{{birdname}}---{{birdname}} and name is {{author}}';
var tpl_end = renderTemplate(template, {
"birdname": "silk",
"author": "David"
});
console.log(tpl_end); // silk---silk and name is David