Click here to Skip to main content
15,886,137 members
Articles / Web Development / HTML
Tip/Trick

String.Format in JavaScript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (15 votes)
27 May 2011CPOL2 min read 209.6K   25   10
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)


Written By
Web Developer
United States United States

  • Managing Your JavaScript Library in ASP.NET (if you work with ASP.net and you don't read that, you are dead to me).
  • Graduated summa cum laude with a BS in Computer Science.
  • Wrote some articles and some tips.
  • DDR ("New high score? What does that mean? Did I break it?"), ping pong, and volleyball enthusiast.
  • Software I have donated to (you should too):

Comments and Discussions

 
QuestionNice One Pin
Mooloolabin10-Oct-14 5:28
Mooloolabin10-Oct-14 5:28 
QuestionAnother suggestion Pin
bizerk8831-Jan-14 18:05
bizerk8831-Jan-14 18:05 
QuestionMy suggestion... Pin
Member 784563021-Jun-12 2:49
Member 784563021-Jun-12 2:49 
SuggestionMore easy form Pin
Cleydson146-Jun-12 3:40
Cleydson146-Jun-12 3:40 
GeneralRe: More easy form Pin
AspDotNetDev6-Jun-12 16:35
protectorAspDotNetDev6-Jun-12 16:35 
GeneralReason for my vote of 5 Nice one Pin
thatraja15-Nov-11 23:19
professionalthatraja15-Nov-11 23:19 
GeneralGood. 5d Pin
Gandalf_TheWhite31-May-11 4:24
professionalGandalf_TheWhite31-May-11 4:24 
GeneralThank you for sharing. Have my 5 Pin
That's Aragon30-May-11 3:42
That's Aragon30-May-11 3:42 
Generalnice.5 Pin
Monjurul Habib29-May-11 6:48
professionalMonjurul Habib29-May-11 6:48 
Generalgood one.. Pin
saxenaabhi625-May-11 18:09
saxenaabhi625-May-11 18:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.