If you’ve been playing around with the SproutCore framework for a bit, you know doubt have come across a line of code that may look something like this:

properties = 'fname lname age address'.w()

The string of words is converted into an array of words using the method w(). Pretty handy. JavaScript, being dynamic and all, allows you to modify an object at runtime. So the SproutCore framework takes advantage of this fact and adds the w() method to JavaScript’s string object.

In a quest to make things easier for you when building a web application, SproutCore also adds other additional handy methods to the string method. One in particular is the fmt() method.

If you’ve ever coded in C or C++, you probably remember printf or sprintf where you formatted a string doing something like the following:

printf( "Stan was born in %i and is %i years old", 1960, 49 );

The function makes it handy to create a string without you having to explicitly concatenate all the characters together and do the necessary conversions. The fmt() method is basically like printf but simpler. Let’s say we create a typical JavaScript string with variables the old fashion way like so:


var beverage = 'White Russian';
var state = 'abides';

var str = 'The Dude ' + state + ' and loves to drink a ' + beverage';

The approach to creating the concatenated string works, but its tedious having to write and may not be as obvious what the final result should be. So using SproutCore we instead do the following:

var str = 'The Dude %@ and loves to drink a %@'.fmt(state, beverage);

Kind of like printf but simpler. In the statement above you’ll notice the %@. %@ is a placeholder in the string to include an argument given to fmt. If order matters you can also append a number to %@, such as in the following:

var str = 'The Dude loves to drink a %@2 and always %@1'.fmt(state, beverage);

Really simple. Now that you have this handy tool in your belt, go ahead and give it a try. Once I figured out about the fmt() method, I started to use it on a more frequent basis to make my life a little bit easier.

Advertisements