Is there a way to write ('{0} {1}'.format(1, 2)) from Python in JavaScript ??
-
Possible duplicate of JavaScript equivalent to printf/string.formatuser2233706– user22337062017-09-08 04:46:24 +00:00Commented Sep 8, 2017 at 4:46
-
Specifically, this answer.user2233706– user22337062017-09-08 13:02:48 +00:00Commented Sep 8, 2017 at 13:02
Add a comment
|
2 Answers
I use the following:
String.prototype.format = function () {
var args = [].slice.call(arguments);
return this.replace(/(\{\d+\})/g, function (a) {
return args[+(a.substr(1, a.length - 2)) || 0];
});
};
Use it like
var testString = 'some string {0}';
testString.format('formatting'); // result = 'some string formatting'
Comments
There are packages providing that functionality and libraries that include it, but nothing built into JavaScript. If your format string is fixed and doesn’t use anything beyond simple interpolation, “template literals” exist in ES6:
`${1} ${2}`
and the obvious ES5 version isn’t terrible:
1 + ' ' + 2