HDRI Community Site

Welcome to HDRI Community Site Sign in | Join | Help
in Search

Ray's blog

JavaScript String.format()

Here's a little bit of javascript that I came up with to aid in formatting strings.

String.prototype.format = function()

{

    var str = this;

 

    for(var i=0;i<arguments.length;i++)

    {

        var re = new RegExp('\\{' + (i) + '\\}','gm');

        str = str.replace(re, arguments[i]);

    }

 

    return str;

}

This will allow you to call the format() method on any string and pass in replacement parameters.  Here's an example:

var firstName = 'Ray';

var lastName = 'Houston';

var hello = 'Hello. My name is {0} {1}.'.format( firstName, lastName );


If you don't like the way that looks (and want a more .NET looking syntax), you can create a static method on the String type like so:

String.format = function()

{

    if( arguments.length == 0 )

        return null;

 

    var str = arguments[0];

 

    for(var i=1;i<arguments.length;i++)

    {

        var re = new RegExp('\\{' + (i-1) + '\\}','gm');

        str = str.replace(re, arguments[i]);

    }

 

    return str;

}


Then the example can be written as:

var firstName = 'Ray';

var lastName = 'Houston';

var hello = String.format('Hello. My name is {0} {1}.', firstName, lastName);


One thing this method doesn't do is that it doesn't allow for escaping '{' or '}' characters. It will still replace {{0}} instead of skipping it like .NET does.
Published Monday, February 27, 2006 6:36 PM by ray

Comments

 

Vinu said:

Hi,

is it possible to pass array to string.format(arrayArgs)?

eg :
var str = "{0},{1},{2}";
var arrayArgs = new Array(2); arrayArgs[0]='1';arrayArgs[1]='2';arrayArgs[2]='2';
string.format(arrayArgs);
March 27, 2007 9:08 PM
 

:: guy parton :: » String::Format for PHP said:

June 18, 2007 4:20 PM
 

bathroom vanities said:

July 31, 2007 9:39 AM
 

bathroom faucets said:

August 2, 2007 2:07 PM
 

bathroom vanity cabinet said:

August 4, 2007 11:43 AM
 

bathroom vanity said:

August 4, 2007 6:56 PM
 

黃偉榮 said:

因為習慣了C#的 String.Format 去組合字串,最近在寫ASP與JavaScript時沒有這個功能實在是有夠不方便。
August 23, 2007 8:26 PM
 

DotNet style String.format function for javascript | ??? said:

April 20, 2008 6:48 AM
 

leen said:

there is a problem:

"{0}".format("{0}")

just wrote my version of string.format
http://leen.name/blog/string-format-for-javascript-dotnetstyle/
April 20, 2008 8:07 AM
Anonymous comments are disabled

This Blog

Post Calendar

<February 2006>
SuMoTuWeThFrSa
2930311234
567891011
12131415161718
19202122232425
2627281234
567891011

Syndication

Powered by Community Server, by Telligent Systems