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();
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:
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/
Your trim method doesn't work when a memory variable carrying a string with leading and trailing spaces is passed to it
Post a Comment
<< Home