1. 最简单
var template = "this is a {img}";
template = template.replace("{img}", "http://xxx");
//this is a http://xxx
2. 如果template中有两个同样的?
var template = "this is a {img}, this {img} is beautiful";
template = template.replace(/{img}/g, "http://xxx");
//this is a http://xxx, this http://xxx is beautiful
3. 如果"key"是不确定的?
var config = {
"img" : "http://xxx",
"title" : "pig"
}
var template = "this is a {title}'s {img}, this {img} is beautiful";
for(var i in config){
template = template.replace(new RegExp("{" + i + "}", "g"), config[i]);
}
//this is a pig's http://xxx, this http://xxx is beautiful
4. 匹配到的
var template = "this is word";
template = template.replace(/(word)/g, "a $1");
//this is a word
5. 更复杂点的就用replace function
var template = "this is word";
template = template.replace(/\s(word)/g, function(word, p1){
//参数
//1. word:整个正则匹配到的 " word" 2. p1:(word)
return " a " + p1 + "," + word; //" a word"
});
//this is a word, word