I would like a javascript function that mimics the python .format() function that works like
.format(*args, **kwargs)
A previous question gives a possible (but not complete) solution for '.format(*args)
JavaScript equivalent to printf/string.format
I would like to be able to do
"hello {} and {}".format("you", "bob"
==> hello you and bob
"hello {0} and {1}".format("you", "bob")
==> hello you and bob
"hello {0} and {1} and {a}".format("you", "bob",a="mary")
==> hello you and bob and mary
"hello {0} and {1} and {a} and {2}".format("you", "bob","jill",a="mary")
==> hello you and bob and mary and jill
I realize that's a tall order, but maybe somewhere out there is a complete (or at least partial) solution that includes keyword arguments as well.
Oh, and I hear AJAX and JQuery possibly have methods for this, but I would like to be able to do it without all that overhead.
In particular, I would like to be able to use it with a script for a google doc.
Thanks
UPDATE: If you're using ES6, template strings work very similarly to
String.format
: https://developers.google.com/web/updates/2015/01/ES6-Template-StringsIf not, the below works for all the cases above, with a very similar syntax to python's
String.format
method. Test cases below.This should work similar to python's
format
but with an object with named keys, it could be numbers as well.