HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

JavaScript equivalent to printf/String.Format

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
equivalentformatstringjavascriptprintf

Problem

I'm looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (IFormatProvider for .NET).

My basic requirement is a thousand separator format for numbers for now, but something that handles lots of combinations (including dates) would be good.

I realize Microsoft's Ajax library provides a version of String.Format(), but we don't want the entire overhead of that framework.

Solution

Current JavaScript

From ES6 on you could use template strings:

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!"


See Kim's answer below for details.

Older answer

Try sprintf() for JavaScript.

If you really want to do a simple format method on your 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 you would expect the output to be {1}{0} but the actual output is {1}{1}. So do a simultaneous replacement instead like in fearphage’s suggestion.

Code Snippets

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!"
"{0}{1}".format("{1}", "{0}")

Context

Stack Overflow Q#610406, score: 1662

Revisions (0)

No revisions yet.