String formatting function in javascript.
Replies: 1   Views: 2075  Subscribers: 1

Posted by reece · 30-06-2012 - 22:44

Edited by reece · 12-11-2012 - 05:01
To the best of my knowledge, javascript does not come with a default string formatter like  most other languages do (such as C/C++, php, Java and C# etc).

This however is not an issue, writing a string formatter in Javascript is relatively easy. 
Here is a function i wrote, it only took a few minutes to write and is relatively simple.

// Formats a string by the number of specified arguments.
function stringFormat() {
	var str = arguments­[0]­;
	var argc = arguments.length;
	$.each(arguments, function(key, argument) {
		if (key == 0) { return true; }
		str=str.replace('{' + (key-1) + '}', argument);
	return str;
As the number of parameters will undoubtedly vary, we don't set any param variables in the function. Instead we make use of the arguments variable that each function has by default. The first parameter must be a string, the remaining parameters can be strings, chars or numeric values. You may add as many additional parameters as you need. Example usage: ­
stringFormat('good {0}, {1}, would you like some {2}?', "morning", "reece", "cereal");­