String.format en Javascript

Dejo a continuacion una funcion bastante util que se comporta como el String.format de Java. En Javascript es comun andar componiendo strings a partir de constantes, variables, literales y otras cosas para generar una salida HTML. Asi que en lugar de escribir:

var v = "<span style='color:"+myColor+"'>"+singleton.myText()+"</span><span id='"+entityId+"'>"+Text+"</span>";

podemos poner:

var v = "<span style='color:{0}'> {1} </span> <span id='{2}'>{3}</span>".format(myColor,singleton.myText(),entityId,Text);

más lindo no?

// Replaces {0},{1},{n} with the arguments.
String.prototype.format = function() {
	var i = 0;
	var string = (typeof (this) == "function" && !(i++)) ? arguments[0] : this;
	while(i < arguments.length) {
		string = string.replaceAll('\\{' + i + '\\}', arguments[i]);
                i++;
        }
	return string;
}
This entry was posted in Javascript and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Captcha
Enter the letters you see above.

35665 pages viewed, 42 today
17305 visits, 10 today
FireStats icon Powered by FireStats