您的位置:首页 > Web前端 > JavaScript

js replace常用用法

2013-04-15 20:21 295 查看
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


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: