Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  121] [ 7]  / answers: 1 / hits: 50267  / 14 Years ago, fri, february 11, 2011, 12:00:00

Python has this beautiful function to turn this:



bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'

foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1
# The lazy dog jumped over the foobar


Into this:



bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'

foo = 'The lazy {} {} over the {}'.format(bar3, bar2, bar1)
# The lazy dog jumped over the foobar


Does JavaScript have such a function? If not, how would I create one which follows the same syntax as Python's implementation?


More From » python

 Answers
78

Another approach, using the String.prototype.replace method, with a replacer function as second argument:



String.prototype.format = function () {
var i = 0, args = arguments;
return this.replace(/{}/g, function () {
return typeof args[i] != 'undefined' ? args[i++] : '';
});
};

var bar1 = 'foobar',
bar2 = 'jumped',
bar3 = 'dog';

'The lazy {} {} over the {}'.format(bar3, bar2, bar1);
// The lazy dog jumped over the foobar

[#93773] Thursday, February 10, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katia

Total Points: 570
Total Questions: 101
Total Answers: 85

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;