Programmatically Speaking ...

This site

Fav Blogs

Sponsors

  • MaximumASP
  • Packet Sniffer

String.format problem with MS AJAX javascript

One of the string method in MS Ajax library is String.format. It works well in a statement like this:

alert(String.format("Format me now, first is {0}, second is {1}, third is {2}", "first", "second", "third"));

However, if you want to put the last three parameters in an array as such:

var values = new array();

values[0] = "first";

values[1] = "second";

values[2] = "third";

Then you run the statement again:

alert(String.format("Format me now, first is {0}, second is {1}, third is {2}", values));

You will found the alerted string is "Format me now, first is first, second, third, second is , third is "

Totally not what it should be.

So instead, we have to go back the old-timer javascript and do a replacement as such 

  

if (values.length > 0) {
                    url = "
Format me now, first is {0}, second is {1}, third is {2}", 
                    for (var i = 0; i < values.length; i++) {
                        var exp = new RegExp('\\{' + (i) + '\\}', 'gm');
                        url = url.replace(exp, valuesIdea);
                    }

Guess we all make mistakes.

var values = new array();

values[0] = "first";

values[1] = "second";

values[2] = "third";

Comments

DotNetBurner - Javascript said:

DotNetBurner - burning hot .net content

# September 12, 2009 5:56 PM

Bleroy said:

Nah, you should be able to work around this like this:

var values = ["first", "second", "third"];

alert(String.format.apply(String, ["Format me now, first is {0}, second is {1}, third is {2}"].concat(values)));

Plus, is String.Format in .NET really working with arrays??

# December 5, 2009 12:54 AM