JavaScript equivalent of Python's format() function?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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?





Look at this thread for a solution: stackoverflow.com/questions/610406/…
– Daniel Doezema
Feb 11 '11 at 21:28






I always use jQuery in many of my sites, so it wouldn't hurt. Does JS allow you to subclass or add functions to string objects?
– Blender
Feb 11 '11 at 21:29





JavaScript is a prototype-based language.. You can extend all objects of a type by enhancing their common prototype.
– zzzzBov
Feb 11 '11 at 21:32





Okay. So String.prototype has nothing to do with Prototype.js? I always though that's what the prototype means...
– Blender
Feb 11 '11 at 21:33


String.prototype





prototype is a feature of the language. The prototypejs library is entirely separate.
– user113716
Feb 11 '11 at 21:42



prototype




10 Answers
10



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


String.prototype.replace


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"





Yep, makes sense. jsfiddle.net/wFb2p/6 I hadn't previously grasped the fact that the function runs once for each match. +1
– user113716
Feb 11 '11 at 22:59






Using a function for replacement also means you can pretty easily extend this to support non=empty placeholders such as 1.
– Duncan
Feb 12 '11 at 15:47


1



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);



jsfiddle - link





How does this work? I am not familiar with the $... in Javascript. Awesome though!
– abalter
Apr 6 '16 at 22:32


$...





Its compatible with ES6
– Yash Mehrotra
Apr 8 '16 at 8:01





This is all pretty interesting but that doesn't solve the problem. The method from ES6 is pointless in many case if we cannot pass it a particular context. What you wrote is mostly just syntactic sugar for string concatenation.
– Loïc Faure-Lacroix
Jul 6 '16 at 21:16





This does solve the problem and if you don't have context, you can easily do things like var message = `My name is $ 'default' and I am $ 'default' years old`;
– HussienK
Feb 2 '17 at 18:53



var message = `My name is $ 'default' and I am $ 'default' years old`;





@shrewmouse: Or just f'My name is name and I am age' in Python 3.6.
– Blender
Apr 10 at 15:49


f'My name is name and I am age'



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.


str.format()


format()



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() ;



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


.match()


while



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





Whoa! That was fast. Thank you!
– Blender
Feb 11 '11 at 21:32





make sure you check that arguments[i] exists.
– zzzzBov
Feb 11 '11 at 21:35


arguments[i]





@zzzzBov: Good point. I was just about to give an update that throws an error if the number of arguments doesn't match the number of found. EDIT: Updated.
– user113716
Feb 11 '11 at 21:37





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.'





Seems good except the first part of the code is kind of pointless as String are technically immutable. You don't really have to concatenate each letters. Simply this_string = this. Should be enough. As you're going to use replace later, the this will not be touched anyway.
– Loïc Faure-Lacroix
Jul 6 '16 at 21:21


this_string = this



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.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard