Please enable JavaScript to view the comments powered by Disqus.

String.Format in JavaScript

A - Introduction

As you know,  C# and VB.NET provide a very convenient method called Format().

That method allows us to format a string easily by passing the template string ( the string contains some the placeholders) and the parameters.

Unfortunately, JavaScript doesn’t support that type of function.

Don’t worry :) In this post,  We’ll create the String.Format in JavaScript.

B - String.Format in JavaScript

Here is the full demo source code for String.Format in JavaScript:

<html> 
<head> 
    <title>JavaScript String.Format</title> 
    <script type="text/javascript"> 
         
        // String.Format function 
        String.prototype.format = function (args) { 
            var str = this;
            return str.replace(String.prototype.format.regex, function(item) { 
                var index = parseInt(item.substring(1, item.length - 1));
                var replace; 
                if (index >= 0) {
                    replace = args[index]; 
                } else if (index === -1) { 
                    replace = "{"; 
                } else if (index === -2) { 
                    replace = "}"; 
                } else { 
                    replace = ""; 
                } 
                return replace; 
            }); 
        }; 
        String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g"); 
         
        // Sample usage 
        var str = "{0} {1} {0}. {-1}^_^{-2}"; 
        str = str.format(["Hello", "World"]); 
        alert(str); 
         
    </script> 
</head> 
</html>

C - Explanation

First, I used the regular expression to find all the number wrapped in curly braces.

The number in curly brace will be the index to look up value in parameters array.

And the value in parameters array will replace the corresponding placeholder.

For convenience, I also created 2 special placeholders:

  • {-1} for { character
  • {-2} for } character

Done! :)