JavaScript Trim functions (L-Trim, R-Trim) to remove Whilespace

During String Operation while we found unwanted spaces before or after the string, we apply trim() functions to remove those spaces. Here in this example I have 4 functions. ltrim, rtrim, trim & isWhitespace.

ltrim function is responsible to remove unwanted space from left side of the string. Similarly rtrim function removes space from right side of the string. When both these functions come together it acts like trim function.

The logic behind ltrim & rtrim functions is quite simple. While removing space from left side of the string I am increasing counter inside a for loop. For each space it checking the characters with isWhitespace function. Similarly to remove space from right side of the string I am reducing the counter.

JavaScript Trim Functions

function ltrim(str) 
{ 
for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++);
return str.substring(k, str.length);
}

function rtrim(str) 
{
for(var j=str.length-1; j>=0 && isWhitespace(str.charAt(j)) ; j--) ;
return str.substring(0,j+1);
}

function trim(str) 
{
return ltrim(rtrim(str));
}

function isWhitespace(charToCheck) 
{
var whitespaceChars = " \t\n\r\f";
return (whitespaceChars.indexOf(charToCheck) != -1);
}