Skip to content

Instantly share code, notes, and snippets.

@wenbing
Created February 8, 2012 09:25
Show Gist options
  • Save wenbing/1767102 to your computer and use it in GitHub Desktop.
Save wenbing/1767102 to your computer and use it in GitHub Desktop.
编写通用字符串替换函数replace, 例如 var a = 'hi, my name is {name}, I am {age} years old, my email is {email}.'; var b = {name:'max', age: 12, email: 'max@gmail.com'}; 执行 replace(a, b) 返回'hi, my name is max, I am 12 years old, my email is max@gmail.com.'
function template(str, obj) {
if(str.indexOf('{') === -1) {
return str;
}
var result = [];
var i, l = str.length;
var start = 0, end = 0, inner = false;
var curr, name, value, search;
for(i = 0; i < l; i++) {
curr = str[i];
if(inner) {
if(curr == '}') {
name = str.substring(start+1, i);
if(value = obj[name]) {
result.push(value);
} else {
result.push(name);
}
inner = false;
} else if(curr == '{') {
search = str.substring(start, i);
result.push(search);
}
} else if(curr != '{' || i == l - 1) { // 当前值不是 '{' 或 最后一个是 '{'
result.push(curr);
}
if(curr == '{') {
start = i;
inner = true;
}
}
return result.join('');
}
var a = '{hi, my name is {name, I am {age} years old, my email is {email}. this is another {name}, test}, {';
var b = {name:'max', age: 12, email: 'max@gmail.com'};
console.log(a);
console.log('');
console.log(template(a, b));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment