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