[Solved-5 Solutions] Javascript equivalent to printf.format - javascript Tutorial
Problem:
JavaScript equivalent to printf/String.Format
Solution 1:
Try sprintf() for JavaScript.
If we want to do a simple format method on our own, don’t do the replacements successively but do them simultaneously.
Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:
"{0}{1}".format("{1}", "{0}")
Normally we would expect the output to be {1}{0}
but the actual output is {1}{1}
Solution 2:
"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")Outputs
ASP is dead, but ASP.NET is alive! ASP {2}
If we prefer not to modify String's prototype:
Gives you familiar:
String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');with the same result:
ASP is dead, but ASP.NET is alive! ASP {2}
Read Also
Python string formatSolution 3:
Learn javascript - javascript tutorial -js- javascript examples - javascript programs
We get this output:
Hello, Gabriel, are we feeling OK?
We can use objects, arrays, and strings as arguments! we got its code and reworked it to produce a new version of String.prototype.format
:
Note the clever Array.prototype.slice.call(arguments)
call -- that means if we throw in arguments that are strings or numbers, not a single JSON-style object, we get C#'s String.Format
behavior almost exactly.
Because Array's slice will force whatever's in arguments into an Array, whether it was originally or not, and the key will be the index (0, 1, 2...) of each array element coerced into a string (eg, "0", so "\\{0\\}" for our first regexp pattern).
Read Also
Java StringsSolution 4:
You can use this:
With this option we can replace strings like these:
'The {0} is dead. Don\'t code {0}. Code {1} that is open source!'.format('ASP', 'PHP');
With our code the second {0} wouldn't be replaced.
Solution 5:
From ES6 on we could use template strings:
Be aware that template strings are surrounded by backticks ` instead of (single) quotes.