3 ms·
I use this little helper in my underground lab: function template(str,data){ for(var i in data){ str=str.replace(new RegExp("{("+i+")}"
by Kilimanjaro 14y ago
I use this little helper in my underground lab:
function template(str,data){
for(var i in data){
str=str.replace(new RegExp("{("+i+")}","g"),data[i])
}
return str
}
It can be used with arrays and object literals as well:
txt = template('hello {name}!',{name:'Jen'})
txt = template('days: {0}, {1} and {2}',['mon','tue','wed'])
GPL and WTFPL just in case.
* Looks coincidentally similar to Fuchs'
- thezilch 14y agoAlso https://gist.github.com/984375 https://gist.github.com/984375
- VMG 14y agoWatch out for for (var prop in obj) {} It may iterate over attributes defined in the objects prototype. The right way to iterate over an object is for(var prop in obj) { if(obj.hasOwnProperty(prop)) doSomethingWith(obj[prop]); } (see http://stackoverflow.com/a/588276 http://stackoverflow.com/a/588276)
- drgath 14y agoWhile true, 'data' should always just be an object-literal. If template() is ever passed an instance of an object, there's something else seriously wrong elsewhere in your script.