Wednesday, September 07, 2005

Javascript is cooler than you thought

We'll write a helper to prove it.

String.prototype.format = function() {
content = this;

if(arguments) {
args = arguments[0] instanceof Array ? arguments[0] : arguments;

for(i = 0; i < args.length; i++) {
regex = new RegExp('\{' + i.toString() + '\}', 'ig');

content = content.replace(regex, args[i].toString());

return content;

alert('{0} is {1}. Yes, I said {0}.'.format('Javascript', 'cool'));

I whipped this up in a couple minutes. It's had no real testing. I wrote something similiar at work, so I don't expect you'll have any problems with this, but no promises. ;)

Also, this should be at least IE6 and Firefox compatible. Been meaning to try it on Safari... The only real concern is that the browser supports the instanceof keyword. If not, there are workarounds online that should do the trick.

Why does the code also accept an Array? So you can write other things like an Array.append(content) method that optionally accepts arguments after the content parameter, sticks them in a new Array like so: for(i = 0; args[i] = arguments[i + 1]; i++);, and then pass the new array to content.format(args).

Tada! Now you not only have a useful Array.append method (this[this.length] to get the next new element), but you also have the equivilent of an Array.append_format in the same method. Now is that slick or what?

Told ya Javascript is cooler than you thought. ;)
Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?