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();


Blogger DMW Technologies said...

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


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