Python has this beautiful function to turn this:
bar1 = \'foobar\'
bar2 = \'jumped\'
bar3 = \'dog\'
foo = \'The lazy \' + bar3 + \' \' + bar2 \' over the \'
For those looking for a simple ES6 solution.
First of all I'm providing a function instead of extending native String prototype because it is generally discouraged.
// format function using replace() and recursion
const format = (str, arr) => arr.length > 1
? format(str.replace('{}', arr[0]), arr.slice(1))
: (arr[0] && str.replace('{}', arr[0])) || str
// Example usage
const str1 = 'The {} brown {} jumps over the {} dog'
const formattedString = formatFn(str1, ['quick','fox','lazy'])
console.log(formattedString)
You can use template literals in JS,
const bar1 = 'foobar'
const bar2 = 'jumped'
const bar3 = 'dog'
foo = `The lazy ${bar3} ${bar2} over the ${bar1}`
I think this was helpful.
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));
In the file
https://github.com/BruceSherwood/glowscript/blob/master/lib/glow/api_misc.js
is a function String.prototype.format = function(args) that fully implements the Python string.format() function, not limited simply to handling character strings.
My own srtipped down version of YAHOO's printf reported by PatrikAkerstrand:
function format() {
return [...arguments].reduce((acc, arg, idx) =>
acc.replace(new RegExp("\\{" + (idx - 1) + "\\}", "g"), arg));
}
console.log(
format('Confirm {1} want {0} beers', 3, 'you')
);