Python has this beautiful function to turn this:
bar1 = \'foobar\'
bar2 = \'jumped\'
bar3 = \'dog\'
foo = \'The lazy \' + bar3 + \' \' + bar2 \' over the \'
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)
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.'
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
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"
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);
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