Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

This question already has an answer here:

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

share|improve this question

marked as duplicate by Satpal javascript Nov 10 '14 at 8:57

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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: stackoverflow.com/questions/2534803/string-format-in-javascript – JasonS Jan 12 at 23:11
    
That'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", but the currently linked one isn't. – ruffin Jun 10 at 14:55
    
'{name} is {mood}'.replace('{name}', 'Tobi').replace('{mood}', 'happy') – ilyaigpetrov Aug 19 at 2:01

4 Answers 4

up vote 32 down vote accepted

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

share|improve this answer
    
a solution that allows for argument formatting, based on actual .net code: stackoverflow.com/questions/2534803/string-format-in-javascript – JasonS Jan 12 at 23:11

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]
    })
};
share|improve this answer
    
This seems to be a better answer since it's not messing with the prototype. – Luke Aug 25 at 0:55

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

share|improve this answer

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>

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.