C#’s String.Format For JavaScript

As a .Net Programmer I enjoy using String.Format frequently when working with strings, particularly in SQL statements. Now I don’t work with SQL in JavaScript but there are still plenty of times that I wish I could just whip out my handy dandy String.Format but sadly JavaScript does support this function…what’s that you say?…it does now?

I decided enough was enough and I extended the String object to include my beloved String.Format.

String.js

function _StringFormatInline()
{
	var txt = this;
	for(var i=0;i<arguments.length;i++)
	{
		var exp = new RegExp('\\{' + (i) + '\\}','gm');
		txt = txt.replace(exp,arguments[i]);
	}
	return txt;
}

function _StringFormatStatic()
{
	for(var i=1;i<arguments.length;i++)
	{
		var exp = new RegExp('\\{' + (i-1) + '\\}','gm');
		arguments[0] = arguments[0].replace(exp,arguments[i]);
	}
	return arguments[0];
}

if(!String.prototype.format)
{
	String.prototype.format = _StringFormatInline;
}

if(!String.format)
{
	String.format = _StringFormatStatic;
}

I have given this feature 2 flavors; inline and static. For all you C#ers you know what a static method is, and inline, well I’ll just show you. Now you can do either of these:

Static

var str = String.format("This is a {0} string using the {1} method.","formatted","static");

Inline

var str = "This is a {0} string using the {1} method.".format("formatted","inline");

And a nice little sample page would go like this.

<html>
<head>
	<title>String Extend</title>
	<script src="String.js"></script>
	<script>

		var str = String.format("This is {0} story about {0} {1}.","my","dog");
		var str2 = "I have 2 friends, {0} and {1}.".format("Doug","Jane");
		alert(str + "\n\n" + str2);

	</script>
</head>
<body>
</body>
</html>

Enjoy!

3 comments on this post

Feb 6, 2009 - 03:02:29

Cool one. I was looking for this type of utility since long.
Thanks Geekdaily team.

Howard says:
Feb 10, 2009 - 01:02:55

Your code is very usefull for me. Thanks very much.

James says:
Jun 12, 2009 - 11:06:57

Here’s my own take on it:

String.format = String.prototype.format = function() {

var i=0;
var string = (typeof(this) == “function” && !(i++)) ? arguments[0] : this;

for (; i < arguments.length; i++)
string = string.replace(/\{\d+?\}/, arguments[i]);

return string;
}