Topic: Message Format (Page 1 of 1) |
|
---|---|
Neurotic (0) Inmate Newly admitted From: |
posted 11-28-2006 08:52
code: /** * The following function will help to format messages in the client side. * Usage: * var s = "My name is {0}.\n\rI like {1}"; * alert(MessageFormat(s,"Yossi","JavaScript")); */ function StringFormatter(){ } StringFormatter.prototype.format = function(str) { var i = 1; while(i < arguments.length){ var delimiter = "{" + (i-1) + "}"; var pos = str.indexOf(delimiter); if(pos > -1){ var s = str.substring(0, pos) + arguments[i]; str = s + str.substring(pos + delimiter.length, str.length); } i++; } return str; } var MessageFormat = new StringFormatter();
|
Paranoid (IV) Inmate From: Norway |
posted 11-28-2006 09:14
Why not using a RegExp ? this way you can use the {index} several times. code: StringFormatter.prototype.format = function( str ) { var i=0; while( ++i<arguments.length ) str = str.replace( new RegExp( '{'+(i-1)+'}', 'g' ), arguments[i] ); return str; } Also the usage seems to be: code: var s = "His name is {0}.\n\rHe likes {1}.\n\r{2} also like {1}."; alert( MessageFormat.format(s,"Yossi","JavaScript","p01"));
|
Nervous Wreck (II) Inmate From: |
posted 11-28-2006 11:04
I agree |