Posted by: msh134 on: November 19, 2008
When working with JavaScript in one of my projects I needed to trim strings and pad them. I googled for a solution and many sources I have got the following codes and sharing with you.
Trimming:
//trimming space from both side of the string
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
//trimming space from left side of the string
String.prototype.ltrim = function() {
return this.replace(/^\s+/,"");
}
//trimming space from right side of the string
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}
Using Trim Functions:
//write the code given above
var str = " black ";
alert("a" + str.trim() + "b"); //result "ablackb"
alert("a" + str.ltrim() + "b"); //result "ablack b"
alert("a" + str.rtrim() + "b"); //result "a blackb"