Topic: Message Format (Page 1 of 1) Pages that link to <a href="http://ozoneasylum.com/backlink?for=28675" title="Pages that link to Topic: Message Format (Page 1 of 1)" rel="nofollow" >Topic: Message Format <span class="small">(Page 1 of 1)</span>\

 
Admon Yossi
Neurotic (0) Inmate
Newly admitted

From:
Insane since: Nov 2006

IP logged posted posted 11-28-2006 08:52 Edit Quote
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();



Enjoy

(Edited by Admon Yossi on 11-28-2006 08:53)

poi
Paranoid (IV) Inmate

From: Norway
Insane since: Jun 2002

IP logged posted posted 11-28-2006 09:14 Edit Quote

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





(Edited by poi on 11-28-2006 09:16)

Admon Yossi
Nervous Wreck (II) Inmate

From:
Insane since: Nov 2006

IP logged posted posted 11-28-2006 11:04 Edit Quote

I agree



Post Reply
 
Your User Name:
Your Password:
Login Options: Remember Me On This Computer
 
Your Text:
Loading...
Options: Show Signature
Enable Slimies
Enable Linkwords

« BackwardsOnwards »

Show Forum Drop Down Menu