Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

String.Format in JavaScript

5.00/5 (15 votes)
27 May 2011CPOL2 min read 211.6K  
A JavaScript function to replace string placeholders with values

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:
C#
String.Format("Hello {0}.", "world"); // Hello 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
<html>
<head>
	<title>JavaScript String.Format</title>
	<script type="text/javascript">
		
		// This is the function.
		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");
		
		// Sample usage.
		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}").

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)