2475

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.

8
  • 4
    Aside all the great answers below, you may want to take a look at this one: stackoverflow.com/a/2648463/1712065 which IMO, is the most efficient solution to this problem. Commented Apr 24, 2015 at 2:54
  • 3
    I wrote a cheap one that uses C-like printf syntax. Commented Jan 28, 2016 at 19:38
  • var search = [$scope.dog, "1"]; var url = vsprintf("earth/Services/dogSearch.svc/FindMe/%s/%s", search); ***For node, you can get your module by "npm install sprintf-js" Commented Apr 29, 2016 at 19:25
  • 6
    Most of the answers here are disappointing. Both printf and String.Format are way more than just simple templating, and the question specifically mentions thousand separators, which none of the simple templating solutions handle. Commented Jan 23, 2021 at 23:01
  • 1
    Besides template string; String.padStart might be the other thing ppl looking for. (See stackoverflow.com/questions/2686855/… ) Commented Feb 19, 2023 at 12:39

62 Answers 62

1 2
3
-1

sprintf() function analog in JavaScript as Vue filter and String.prototype.format() extension:

/** * Returns a formatted string. * * @param template * @param values * @return string */ String.format = function (template, ...values) { let i = -1; function callback(exp, p0, p1, p2, p3, p4) { if (exp === '%%') return '%'; if (values[++i] === undefined) return undefined; exp = p2 ? parseInt(p2.substr(1)) : undefined; let base = p3 ? parseInt(p3.substr(1)) : undefined; let val; switch (p4) { case 's': val = values[i]; break; case 'c': val = values[i][0]; break; case 'f': val = parseFloat(values[i]).toFixed(exp); break; case 'p': val = parseFloat(values[i]).toPrecision(exp); break; case 'e': val = parseFloat(values[i]).toExponential(exp); break; case 'x': val = parseInt(values[i]).toString(base ? base : 16); break; case 'd': val = parseFloat(parseInt(values[i], base ? base : 10).toPrecision(exp)).toFixed(0); break; } val = typeof (val) == 'object' ? JSON.stringify(val) : val.toString(base); let sz = parseInt(p1); /* padding size */ let ch = p1 && p1[0] === '0' ? '0' : ' '; /* isnull? */ while (val.length < sz) val = p0 !== undefined ? val + ch : ch + val; /* isminus? */ return val; } let regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g; return template.replace(regex, callback); } String.prototype.format = function() { return String.format(this, ...arguments); } const StringFormat = { install: (Vue, options) => { Vue.filter('format', function () { return String.format(...arguments); }); }, }; export default StringFormat; 

Original answer: JavaScript equivalent to printf/String.Format

Sign up to request clarification or add additional context in comments.

Comments

-1

If you need a printf, use printf

Looks like 90% of commenters never used printf with more complex format than just %d. I wonder how do they output, for example, money values?

1 Comment

Formatting outside the string. (213.3244).toFixed(2) exists in JavaScript, other languages have other methods (C# has Decimal.Truncate(), or you use Math.Round()/Math.round()). Cultural information is also present in many languages. System.Globalization for C# is an example, (324).toLocaleString() in JavaScript. This answer also only works in Node.js, not the browser. Considering the question doesn't specify if its browser or node, this answer could be considered rather useless to the situation (tho helpful to others coming here). Template strings are the best solution here.
1 2
3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.