Tuesday, 13 September 2011

Trim Functions in JavaScript

Three type of trims are available
1. Trim (Left and Right)
2. Right Trim
3. Left Trim

The function for these trims are
Trim
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g,"");
}
Left Trim
String.prototype.ltrim = function()
 {
return this.replace(/^\s+/,"");
}

Right Trim
String.prototype.rtrim = function()
 {
return this.replace(/\s+$/,"");
}


Simply places these function into your page or external javascript file but it must be availble where you will use these functions.

We see how to use these functions

var sampleString="  this is my blog   ";
alert("$"+sampleString.trim()+"$");
alert("$"+sampleString.ltrim()+"$");
alert("$"+sampleString.rtrim()+"$");

                                             

No comments:

Post a Comment