Click here to Skip to main content
Click here to Skip to main content

Tagged as

String.Format in JavaScript

, 27 May 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
A JavaScript function to replace string placeholders with values


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"); // Hello world.
While JavaScript doesn't come with a function to do this, we can create one that acts very similar.


Here is a complete sample that shows how to create a Format() function in JavaScript:
	<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"]);
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}").


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


About the Author

Web Developer
United States United States
  • Managing Your JavaScript Library in ASP.NET (if you work with 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 PinmemberMooloolabin10-Oct-14 6:28 
QuestionAnother suggestion [modified] Pinmemberbizerk8831-Jan-14 19:05 
QuestionMy suggestion... PinmemberMember 784563021-Jun-12 3:49 
SuggestionMore easy form PinmemberCleydson146-Jun-12 4:40 
GeneralRe: More easy form PinprotectorAspDotNetDev6-Jun-12 17:35 
GeneralReason for my vote of 5 Nice one Pinmvpthatraja16-Nov-11 0:19 
GeneralGood. 5d PinmemberGandalf - The White31-May-11 5:24 
GeneralThank you for sharing. Have my 5 PinmemberThat's Aragon30-May-11 4:42 
Generalnice.5 PinmemberMonjurul Habib29-May-11 7:48 
Generalgood one.. Pinmembersaxenaabhi625-May-11 19:09 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150123.1 | Last Updated 27 May 2011
Article Copyright 2011 by AspDotNetDev
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid