Introduction
C# and VB.NET have a nifty
Format()
function that allows you to pass in a template string (a string that contains placeholders) and some parameters, and it replaces the placeholders from the template string with the parameter values. For example:
String.Format("Hello {0}.", "world");
While JavaScript doesn't come with a function to do this, we can create one that acts very similar.
Example
Here is a complete sample that shows how to create a
Format()
function in JavaScript:
<html>
<head>
<title>JavaScript String.Format</title>
<script type="text/javascript">
String.prototype.format = function (args) {
var str = this;
return str.replace(String.prototype.format.regex, function(item) {
var intVal = parseInt(item.substring(1, item.length - 1));
var replace;
if (intVal >= 0) {
replace = args[intVal];
} else if (intVal === -1) {
replace = "{";
} else if (intVal === -2) {
replace = "}";
} else {
replace = "";
}
return replace;
});
};
String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");
var str = "She {1} {0}{2} by the {0}{3}. {-1}^_^{-2}";
str = str.format(["sea", "sells", "shells", "shore"]);
alert(str);
</script>
</head>
</html>
Save the above to an HTML file and run it in your browser. You will see a dialog that says:
She sells seashells by the seashore. {^_^}
How it Works
A regular expression is used to find numbers wrapped with curly braces. The number in the curly brace corresponds to the argument index to lookup. The value at that argument index will be inserted in place of the curly brace placeholder. For convenience, I've also created some special placeholders. If "
{-1}
" is passed in, it will be replaced with "
{
" and if "
{-2}
" is passed in, it will be replaced with "
}
".
JavaScript Regular Expression
While I've seen a few implementations of this functionality in JavaScript, none of them seemed to use this approach. Some looked at each character in the string using a loop, and others used a regular expression to search for each placeholder ("
{0}
", "
{1}
", and so on) in succession. However, this implementation takes advantage of an overload of the
replace()
function that takes a regular expression and a function as parameters. The regular expression is used to find placeholders to replace and the function is passed each of those placeholders, returning the string to replace it with. This is useful because the string only needs to be scanned once, so performance is improved and we avoid the issue of recursive replaces (e.g., when "
{0}
" is replaced with "
{0}
").