Mattking32
Mattking32

Reputation: 1

Is there a function similar to .format() from Python in Javascript?

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

Upvotes: 0

Views: 188

Answers (2)

Ry-
Ry-

Reputation: 224983

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

Upvotes: 1

progrAmmar
progrAmmar

Reputation: 2670

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'

Upvotes: 1

Related Questions