Friday, July 18, 2008

Trimming spaces in JavaScript

This is the first of the series of Tutorials I plan to put on this blog for whosoever might be in need of such information. Much more elaborate tutorials will be put up soon on GWT, GWT-Ext, Swift3D, Papervision3D and a host of other technologies.

Programming in Java and PHP has given me the impression that the trim() method which can be found in the aforementioned languages will be present in most popular languages. To my dismay, I looked hard for that function in the String class while doing some JavaScript coding recently. Luckily enough I did eventually stumble upon the regular expression that would help to trim leading spaces as well as trailing spaces in a string. It's as follows:

var s = " Adobe Flex is a good technology for implementing RIAs ";

//To remove leading spaces, i.e.spaces before the string s, use
s = s.replace( /^\s+/g,'');

//To remove trailing spaces, i.e.spaces after the string s, use
s = s.replace( /\s+$/g,'');

//To remove both spaces(i.e.both leading and trailing), use
s = s.replace( /^\s+/g,'').replace(/\s+$/g,'');

You never know, it might come in handy someday.