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?
The format() method returns a string with a language-specific representation of the list.
The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.
JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values (UTF-16 code units). Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on.
format()) is technique of the string category permits you to try and do variable substitutions and data formatting. It enables you to concatenate parts of a string at desired intervals through point data format.
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);
jsfiddle - link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With