Looking for a good JavaScript equivalent of the C/PHP `printf()` or for C#/Java programmers, `String.Format()` (or `IFormatProvider` for .NET)?

I’m looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (or 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.

Hi,

From ES6 onwards, you can use template strings:

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

If you want to create a simple format method on your own, don’t perform the replacements successively but do them simultaneously.

Many other proposals fail when a replace string from a previous replacement contains a format sequence. For example:

"{0}{1}".format("{1}", "{0}")

Normally, you would expect the output to be {1}{0}, but the actual output is {1}{1}. To avoid this, perform simultaneous replacements as suggested by fearphage.

First, check if format is not yet implemented for the String prototype:

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] !== 'undefined'
        ? args[number]
        : match;
    });
  };
}

// Usage
console.log("{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 you prefer not to modify the String prototype:

if (!String.format) {
  String.format = function(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] !== 'undefined'
        ? args[number] 
        : match;
    });
  };
}

// Usage
console.log(String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET'));
// Outputs: "ASP is dead, but ASP.NET is alive! ASP {2}"

These methods provide a way to format strings similarly to printf() in C or String.Format() in C#.

Here’s a simple function to format strings:

String.prototype.format = function() {
    var formatted = this;
    for (var arg in arguments) {
        if (arguments.hasOwnProperty(arg)) {
            formatted = formatted.replace("{" + arg + "}", arguments[arg]);
        }
    }
    return formatted;
};

// Usage
console.log("{0} is dead, but {1} is alive!".format("ASP", "ASP.NET"));
// Outputs: "ASP is dead, but ASP.NET is alive!"

This function works similarly to string.format:

console.log("{0} is dead, but {1} is alive!".format("ASP", "ASP.NET"));