Tuesday, March 21, 2006

Javascript trivia

One of my ex-colleagues was very passionate about Javascript and used to say that Javascript is one of the most misinterpreted and misused language by the developers. I had to recollect this while developing a trivial trim() function. Though there are many ways to implement the trim() functionality, I wanted to do it in a different (um, adventurous way). I explored a bit and found that there is something called "Prototype" for each of the data types used and new functions can be added dynamically. In this case, I wanted to add a trim function, so the following code would add a function called trim to the String data type

String.prototype.trim = function() { }

And now, filling up the function, I used Regular expressions, the leading spaces can be removed by

str=str.replace(/^\s*(.*)/, "$1");

and the trailing spaces by

str=str.replace(/(.*?)\s*$/, "$1");


The whole code would look like

String.prototype.trim = function() {
var str=this;
str=str.replace(/^\s*(.*)/, "$1");
str=str.replace(/(.*?)\s*$/, "$1");
return str;
}

This is may be a trivial discovery but now it has helped us a lot in the Javascipt code, instead of calling trim(str), we can just say str.trim().