Is there a way to write ('{0} {1}'.format(1, 2))
from Python in JavaScript ??
Asked
Active
Viewed 164 times
0

Mattking32
- 1
- 1
-
Possible duplicate of [JavaScript equivalent to printf/string.format](https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format) – user2233706 Sep 08 '17 at 04:46
-
Specifically, [this answer](https://stackoverflow.com/a/4673436/2233706). – user2233706 Sep 08 '17 at 13:02
2 Answers
1
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'

progrAmmar
- 2,606
- 4
- 29
- 58
1
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

Ry-
- 218,210
- 55
- 464
- 476