Wednesday 21 November 2012

JavaScript Trim() Function



There is no such function in JavaScript to remove the spaces at the beginning and end of the string. But you can use the following approaches to perform Trim operation 


There are two approaches to Trim String


Trim String Using Javascript Function

// Trim Function call Right Trim and Left Trim function to trim string
function trim(myString)
{
      return LeftTrim(RightTrim(myString));
}


function LeftTrim(myString)
{
      for(var k = 0; k < myString.length && IsWhitespace(myString.charAt(k)); k++);
      return myString.substring(k, myString.length);
}

function RightTrim(myString)
{
      for(var j=myString.length-1; j>=0 && IsWhitespace(myString.charAt(j)) ; j--) ;
      return myString.substring(0,j+1);
}
function IsWhitespace(charToCheck) {
      var whitespaceChars = " \t\n\r\f";
      return (whitespaceChars.indexOf(charToCheck) != -1);
}


Trim string using Regular Expression
Function Trim(myString)    
{    
    return myString.replace(/^s+/g,'').replace(/s+$/g,'')    
}

No comments:

Post a Comment