Wednesday, June 18, 2008

Trim in JavaScript


To Trim space in a word


Left Trim Function to trim the space in the left side of the string

function ltrim ( s ){
return s.replace( /^\s*/, "" );
}

Right Trim Function to trim the space in the right side of the string

function rtrim ( s ){
return s.replace( /\s*$/, "" );
}

Trim Function to trim the space in the string

function trim(s) {
var temp = s;
return temp.replace(/^\s+/,'').replace(/\s+$/,'');
}

2 comments:

Rochak Chauhan said...

You can also use
http://rochakchauhan.com/blog/2008/10/10/rochakjs-javascript-class-of-common-functions/
It contains many commonly needed functions for JavaScript including trim();

Daniel said...

Thanks Rochak!