JavaScript equivalent of Python's format() function?

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?

Answers


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"

There is a way, but not exactly using format.

 
    var name = "John";
    var age = 19;
    var message = `My name is ${name} and I am ${age} years old`;
    console.log(message);

Looking for an answer for the same question, I just found this: https://github.com/davidchambers/string-format, which is "JavaScript string formatting inspired by Python’s str.format()". It seem it's pretty much the same as python's format() function.


Taken from YAHOOs library:

YAHOO.Tools.printf = function() { 
  var num = arguments.length; 
  var oStr = arguments[0];   
  for (var i = 1; i < num; i++) { 
    var pattern = "\\{" + (i-1) + "\\}"; 
    var re = new RegExp(pattern, "g"); 
    oStr = oStr.replace(re, arguments[i]); 
  } 
  return oStr; 
} 

Call it like:

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

foo = YAHOO.Tools.printf('The lazy {0} {1} over the {2}', bar3, bar2, bar1); 

Here's my first attempt. Feel free to point out flaws.

Example: http://jsfiddle.net/wFb2p/5/

String.prototype.format = function() {
    var str = this;
    var i = 0;
    var len = arguments.length;
    var matches = str.match(/{}/g);
    if( !matches || matches.length !== len ) {
        throw "wrong number of arguments";
    }
    while( i < len ) {
        str = str.replace(/{}/, arguments[i] );
        i++;
    }
    return str;
};

EDIT: Made it a bit more efficient by eliminating the .match() call in the while statement.

EDIT: Changed it so that the same error is thrown if you don't pass any arguments.


tl;dr
foo = (a, b, c) => `The lazy ${a} ${b} over the ${c}`
Why template strings alone aren't enough

ES6 template strings provide a feature quite similar to pythons string format. However, you have to know the variables before you construct the string:

var templateString = `The lazy ${bar3} ${bar2} over the ${bar1}`;
Why format?

Python's str.format allows you to specify the string before you even know which values you want to plug into it, like:

foo = 'The lazy {} {} over the {}'

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

foo.format(bar3, bar2, bar1)
Solution

With an arrow function, we can elegantly wrap the template string for later use:

foo = (a, b, c) => `The lazy ${a} ${b} over the ${c}`

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

foo(bar3, bar2, bar1)

Of course this works with a regular function as well, but the arrow function allows us to make this a one-liner. Both features are available in most browsers und runtimes:


This code allows you to specify exactly which brackets to replace with which strings. The brackets don't need to be in the same order as the arguments, and multiple brackets are possible. The format function takes an array of values as its parameter, with each key being one of the bracketed 'variables' which is replaced by its corresponding value.

String.prototype.format = function (arguments) {
    var this_string = '';
    for (var char_pos = 0; char_pos < this.length; char_pos++) {
        this_string = this_string + this[char_pos];
    }

    for (var key in arguments) {
        var string_key = '{' + key + '}'
        this_string = this_string.replace(new RegExp(string_key, 'g'), arguments[key]);
    }
    return this_string;
};

'The time is {time} and today is {day}, {day}, {day}. Oh, and did I mention that the time is {time}.'.format({day:'Monday',time:'2:13'});
//'The time is 2:13 and today is Monday, Monday, Monday. Oh, and did I mention that the time is 2:13.'

JS:

String.prototype.format = function () {
    var str = this;
    for (var i = 0; i < arguments.length; i++) {
        str = str.replace('{' + i + '}', arguments[i]);
    }
    return str;
}

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

python_format = 'The lazy {2} {1} over the {0}'.format(bar1,bar2,bar3);

document.getElementById("demo").innerHTML = "JavaScript equivalent of Python's format() function:<br><span id='python_str'>" + python_format + "</span>";

HTML:

<p id="demo"></p>

CSS:

span#python_str {
    color: red;
    font-style: italic;
}

OUTPUT:

JavaScript equivalent of Python's format() function:

The lazy dog jumped over the foobar

DEMO:

jsFiddle


JavaScript doesn't have such a function AFAIK.

You could create one by modifying the String class's prototype object to add a format() method which takes a variable number of arguments.

In the format method you'd have to get the String's instance value (the actual string) and then parse it for '{}' and insert the appropriate argument.

Then return the new string to the caller.


JavaScript does not have a string formatting function by default, although you can create your own or use one someone else has made (such as sprintf)


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.


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)

Need Your Help

Importing CSV data using PHP/MySQL

php mysql database csv import

I'm having a bit of a problem trying to import data from a CSV and have a couple of questions on it that I haven't managed to solve myself yet.

A generic singleton

c# singleton generics

What do you guys think about this for a generic singleton?