Javascript built-in printf-like function

Browsers such as Chrome and Firefox offer an API console that allows you to highlight formatted log messages, for example:

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

Now suppose I want to generate a formatted string, but it is not necessary to write it to the console. Does the browser provide a built-in function that creates log lines? Is it an ECMA-stardard? Or should we be content with third-party libraries like JavaScript sprintf ?

+4
source share
2 answers

ES6 will introduce some basic string formatting in the form:

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

But there is currently no native string formatting in ES5.

+4
source

I do not think you can do this initially. You can write your own javascript toString function to handle various parameters.

Alternatively you could do

 var samuel = "sam"; var someNumber = 100; var someString = samuel + " has " + someNumber + " points"; 
0
source

All Articles