Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Native Javascript printf-like function

Browsers such as Chrome and Firefox offer a console API that enable the emission of formatted log messages, like this:

>>> console.log("%s has %d points", "Sam", "100");
Sam has 100 points

Now, suppose I want to generate a formatted string but not necessarily log it into the console. Do the browsers expose the native function that produces the log strings? Is it ECMA-stardard? Or should we be content with third party libraries such as JavaScript sprintf for now?

like image 336
Humberto Avatar asked Apr 04 '13 18:04

Humberto


People also ask

Does JavaScript have printf?

In JavaScript, the “console. log” method is used to print the value of some integer or string. You can also utilize this method for printing the integer and string values as an equivalent to printf.

What is%# in printf?

%#G Always show the decimal point trailing zeros not removed. The flags must follow the %. Where it makes sense, more than one flag can be used.

What is string formatting in JavaScript?

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.


1 Answers

ES6 will introduce some basic string formatting in the form of:

`${name} has ${val} points`;

But there's currently no native string formatting in ES5.

like image 193
Kevin Ennis Avatar answered Oct 29 '22 00:10

Kevin Ennis