Created
February 8, 2012 09:25
-
-
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: '[email protected]'}; 执行 replace(a, b) 返回'hi, my name is max, I am 12 years old, my email is [email protected].'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: '[email protected]'}; | |
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