Python has this beautiful function to turn this:
bar1 = \'foobar\'
bar2 = \'jumped\'
bar3 = \'dog\'
foo = \'The lazy \' + bar3 + \' \' + bar2 \' over the \'
Usando split:
String.prototype.format = function (args) {
var text = this
for(var attr in args){
text = text.split('${' + attr + '}').join(args[attr]);
}
return text
};
json = {'who':'Gendry', 'what':'will sit', 'where':'in the Iron Throne'}
text = 'GOT: ${who} ${what} ${where}';
console.log('context: ',json);
console.log('template: ',text);
console.log('formated: ',text.format(json));
Usando Regex:
String.prototype.format = function (args) {
var text = this
for(var attr in args){
var rgx = new RegExp('${' + attr + '}','g');
text = text.replace(rgx, args[attr]);
}
return text
};
json = {'who':'Gendry', 'what':'will sit', 'where':'in the Iron Throne'}
text = 'GOT: ${who} ${what} ${where}';
console.log('context: ',json);
console.log('template: ',text);
console.log('formated: ',text.format(json));