Click here to Skip to main content
12,449,762 members (83,076 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

107.4K views
24 bookmarked
Posted

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

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"); // 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>
<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)

Share

About the Author

AspDotNetDev
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):

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionNice One Pin
Mooloolabin10-Oct-14 5:28
memberMooloolabin10-Oct-14 5:28 
QuestionAnother suggestion Pin
bizerk8831-Jan-14 18:05
memberbizerk8831-Jan-14 18:05 
QuestionMy suggestion... Pin
Member 784563021-Jun-12 2:49
memberMember 784563021-Jun-12 2:49 
SuggestionMore easy form Pin
Cleydson146-Jun-12 3:40
memberCleydson146-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
mvpthatraja15-Nov-11 23:19 
GeneralGood. 5d Pin
Gandalf - The White31-May-11 4:24
memberGandalf - The White31-May-11 4:24 
GeneralThank you for sharing. Have my 5 Pin
That's Aragon30-May-11 3:42
memberThat's Aragon30-May-11 3:42 
Generalnice.5 Pin
Monjurul Habib29-May-11 6:48
memberMonjurul Habib29-May-11 6:48 
Generalgood one.. Pin
saxenaabhi625-May-11 18:09
membersaxenaabhi625-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.

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