Tuesday, January 04, 2005

trim method in JavaScript

JavaScript does not contain a method for trimming strings. You can create one for yourself and use it whereever you want to trim strings.

STEP 1: JavaScript Methods

The first step is to create the methods for trimming the strings. This can be done using regular expressions.

function strltrim()
{
return this.replace(/^\s+/,'');
}

function strrtrim()
{
return this.replace(/\s+$/,'');
}

function strtrim()
{
return this.replace(/^\s+/,'').replace(/\s+$/,'');
}

String.prototype.ltrim = strltrim;
String.prototype.rtrim = strrtrim;
String.prototype.trim = strtrim;


STEP 2: Usage

//To remove the leading blanks from a string variable
sTextsText = sText.ltrim();
//To remove the trailing blanks from a string variable
sTextsText = sText.rtrim();
//To remove the leading and trailing blanks from a string variable
sTextsText = sText.trim();

2 Comments:

Blogger Rochak Chauhan said...

There are many required functions which are not available in Native JavaScript.Get trim and more functions like trim() for JavaScript:

http://rochakchauhan.com/blog/2007/10/08/rochakjs-javascript-class-of-common-functions/

9:47 AM  
Anonymous Anonymous said...

Your trim method doesn't work when a memory variable carrying a string with leading and trailing spaces is passed to it

3:40 AM  

Post a Comment

<< Home