Search The Blog!

Google
  Web codingtips.blogspot.com

Monday, July 19, 2004

JavaScript Function to Trim White Space (RTRIM)

Like the LTRIM previously posted, this function trims white space, but from the right of the text.


/*
RTrim - Trims whitespace from right of a string
*/
function RTrim(str)
{
var whitespace = new String(" \t\n\r");

var s = new String(str);

if (whitespace.indexOf(s.charAt(s.length-1)) != -1)
{
var i = s.length - 1; // Get length of string
while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
i--;
s = s.substring(0, i+1);
}

return s;
}

Jonathan Leger