Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 562
Blender Avatar asked Feb 11 '11 21:02

Blender


People also ask

What is format method in JavaScript?

The format() method returns a string with a language-specific representation of the list.

What is format () function in Python?

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.

Does JavaScript have string format?

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.

Which type for function format () is?

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.


2 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" 
like image 106
Christian C. Salvadó Avatar answered Oct 12 '22 08:10

Christian C. Salvadó


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

like image 22
Yash Mehrotra Avatar answered Oct 12 '22 08:10

Yash Mehrotra