Topic: Message Format (Page 1 of 1) Pages that link to <a href="https://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

posted 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();



Enjoy

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

poi
Paranoid (IV) Inmate

From: Norway
Insane since: Jun 2002

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





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

Admon Yossi
Nervous Wreck (II) Inmate

From:
Insane since: Nov 2006

posted posted 11-28-2006 11:04

I agree



Post Reply
 
Your User Name:
Your Password:
Login Options:
 
Your Text:
Loading...
Options:


« BackwardsOnwards »

Show Forum Drop Down Menu