85

C# has the really powerful String.Format() for replacing elements like {0}with parameters. Does JavaScript have an equivalent?

hopper
  • 13,060
  • 7
  • 49
  • 53
David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • 3
    There's no built-in equivalent, but you may google for external libraries. – kirilloid Aug 23 '13 at 14:48
  • 2
    Another option is CoffeeScript, which has Ruby style string interpolation. – Matt Greer Aug 23 '13 at 14:49
  • a solution that allows for argument formatting, based on actual .net code: https://stackoverflow.com/questions/2534803/string-format-in-javascript – JasonS Jan 12 '15 at 23:11
  • 4
    [That](http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery)'s the wrong duplicate. This is a question about string.format in **JavaScript**, and the dupe is for **jQuery**. `JavaScript !== jQuery`. There's not even a jQuery tag. You could argue [this question ("JavaScript equivalent to printf/string.format") is the correct "original"](http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format), but the currently linked one isn't. – ruffin Jun 10 '15 at 14:55
  • `'{name} is {mood}'.replace('{name}', 'Tobi').replace('{mood}', 'happy')` – ilyaigpetrov Aug 19 '15 at 02:01
  • 2
    We're looking for a __non-jQuery__ answer. How can you mark the jQuery post as a duplicate for this question? That's supremely ignorant on part of those collective users who voted to close this off. Voting to reopen, btw. – code4life Jan 05 '17 at 16:06
  • So the correct answer is "no". Thanks for marking it as duplicate of a completely different question where everyone actually ignores the jquery part and modifies the string prototype with some custom code... the answer is just no, there isn't. You can write one, sure, but there isn't one built in. – Luc Apr 01 '19 at 14:19

4 Answers4

92

Try sprintf() for javascript.

Or

// First, checks if it isn't implemented yet.
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
      ;
    });
  };
}

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

Both answers pulled from JavaScript equivalent to printf/string.format

Community
  • 1
  • 1
Scott
  • 13,735
  • 20
  • 94
  • 152
  • a solution that allows for argument formatting, based on actual .net code: https://stackoverflow.com/questions/2534803/string-format-in-javascript – JasonS Jan 12 '15 at 23:11
  • If you don't want to extend the prototype: `export class String { //String.format("{0} comes before {1}", "a", "b") static format(stringToFormat, ...tokens) { return stringToFormat.replace(/{(\d+)}/g, function (match, number) { return typeof tokens[number] != 'undefined' ? tokens[number] : match; }); }; }` – miraco Mar 20 '18 at 12:36
  • 1
    Yeah, I think it's a bad practice to extend the prototype of standard objects. – wm1sr Jan 07 '19 at 21:32
  • Basically Logic is `return stringToFormat.replace(/{(\d+)}/g, function (match, number) { return typeof tokens[number] != 'undefined' ? tokens[number] : match; }); ` you can put this in normal method just like below : `function format(stringToFormat, ...tokens) { return stringToFormat.replace(/{(\d+)}/g, function (match, number) { return typeof tokens[number] != 'undefined' ? tokens[number] : match; }); }; ` – Vinod Poorma Jul 14 '23 at 13:02
32

I am using:

String.prototype.format = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

usage: "Hello {0}".format("World");

I found it at Equivalent of String.format in JQuery

UPDATED:

In ES6/ES2015 you can use string templating for instance

'use strict';

let firstName = 'John',
    lastName = 'Smith';

console.log(`Full Name is ${firstName} ${lastName}`); 
// or
console.log(`Full Name is ${firstName + ' ' + lastName}');
Community
  • 1
  • 1
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
  • 5
    Although string templating is a nice feature, it's not the same thing. You can't store the string in memory or otherwise (in a registry for example) and use it with whatever inputs at a later point during runtime. – Mike Haas Sep 29 '16 at 20:29
17

Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:

String.prototype.format = function(placeholders) {
    var s = this;
    for(var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }    
    return s;
};

usage:

"{greeting} {who}!".format({greeting: "Hello", who: "world"})

String.prototype.format = function(placeholders) {
    var s = this;
    for(var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }    
    return s;
};

$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
t3chb0t
  • 16,340
  • 13
  • 78
  • 118
15

I created it a long time ago, related question

String.Format = function (b) {
    var a = arguments;
    return b.replace(/(\{\{\d\}\}|\{\d\})/g, function (b) {
        if (b.substring(0, 2) == "{{") return b;
        var c = parseInt(b.match(/\d/)[0]);
        return a[c + 1]
    })
};
Community
  • 1
  • 1
BrunoLM
  • 97,872
  • 84
  • 296
  • 452