Tuesday, November 17, 2009

C# like trim(),trimStart(),trimEnd() function in javascript

String.prototype.trimStart=function(c)
{
c = c?c:' ';
var i=0;
for(;i<this.length && this.charAt(i)==c; i++);
return this.substring(i);
}
String.prototype.trimEnd=function(c)

{
c = c?c:' ';
var i=this.length-1;
for(;i>=0 && this.charAt(i)==c;i--);
return this.substring(0,i+1);
}
String.prototype.trim=function(c)
{
return this.trimStart(c).trimEnd(c);
}
Example:
" anil soni ".trim()

1 comment:

Elrinth said...

Your code was great, but I'm guessing you missed a few chars. Anyways, here's corrected code plus a leadingUpper function:

String.prototype.trimStart = function (c) {
if (this.length == 0)
return this;
c = c ? c : ' ';
var i = 0;
var val = 0;
for (; this.charAt(i) == c && i < this.length; i++);
return this.substring(i);
}

String.prototype.trimEnd=function(c)
{
c = c?c:' ';
var i=this.length-1;
for(;i>=0 && this.charAt(i)==c;i--);
return this.substring(0,i+1);
}
String.prototype.trim=function(c)
{
return this.trimStart(c).trimEnd(c);
}
String.prototype.leadingUpper = function () {
var result = "";
if (this.length > 0) {
result += this[0].toUpperCase();
if (this.length > 1)
result += this.substring(1, this.length);
}
return result;
}