DHTMLdev.com — Dedicated to quality Web development articles and tutorials
Creating a Trim Function in JavaScript PDF Print E-mail
Tuesday, 27 December 2005

Many languages have a built-in trim function or method, to remove leading and trailing whitespace from a string of some sort. JavaScript, however, does not. So I wrote one and will explain how it works. Plus, I wrote two versions: one using a while loop and another one using recursion.

Table of Contents

  1. What Does a Trim Function Do?
  2. Writing a Trim Function
  3. Using the Trim Function

What Does a Trim Function Do?

A trim function is very useful for cleaning up extra whitespace around a piece of text, such as user input in a form or text from a data file. One can easily imagine needing to clean up form data entered by users, but that could also be done on the server side without JavaScript. Here's another example. Recently, I wrote several HomeSite actionscripts to reformat text pasted in from Microsoft Word and Excel documents. One part of my code needed to deal with extra whitespace.

// This text pasted from Microsoft Word
"   First item
   o   First sub item
   o   Second sub item
"   Second item
"   Third item
 
// Needed to be reformatted into this HTML
<ul>
<li>First item
<ul>
<li>First sub item</li>
<li>Second sub item</li>
</li>
</ul>
<li>Second item</li>
<li>Third item</li>
</ul>
 

In Word, a list is copied and pasted into a new text document, such as an HTML document, as a series of line returns, extra whitespace, double quote characters, and small letter o characters. Why?—I don't know. But they are. And it was my job to write a program to clean them up. Part of that job included getting rid of the extra whitespace: enter my new trim function.

A trim function should be designed to remove whitespace only from the beginning and end of a string, not whitespace within a string. So your trim function should not simply remove whitespace, which would remove all spaces between words. It should remove whitespace just from the beginning and from the end of the string.

Writing a Trim Function

Basically, this is how a trim function works. First, the code must identify the first character of the string it is operating on, and if that first character is a whitespace character, delete it and save the string. Then repeat this process over and over again, until there are no more whitespace characters at the front of the string. Next, the function should repeat this process at the end of the string to remove all whitespace characters at the end.

Now, the way in which the function repeats this process can be implemented in two ways: 1) using recursion; and 2) using a while loop. I love recursion, but a while loop works just as well and is easier to understand. I do not know which one is faster and it doesn't matter, unless you will be processing thousands of strings at a time in a performance critical operation. In that case, I imagine that the while loop would be faster and the best choice, but if it's that important, you should test the two different functions below yourself and not take my word for it. Here is the code. You need only one of the two functions. I show both to illustrate both ways of writing a trim function.

// This function uses recursion
function TrimUsingRecursion(str) 
{  if(str.charAt(0) == " ")
  {  str = TrimUsingRecursion(str.substring(1));
  }
  if (str.charAt(str.length-1) == " ")
  {  str = TrimUsingRecursion(str.substring(0,str.length-1));
  }
  return str;
}
 
// This function uses a while loop
function TrimUsingWhileLoop(str)
{  while(str.charAt(0) == (" ") )
  {  str = str.substring(1);
  }
  while(str.charAt(str.length-1) == " " )
  {  str = str.substring(0,str.length-1);
  }
  return str;
}

Using the Trim Function

Which ever way (recursion or the while loop) you prefer to implement, just name that function to Trim and start using it. I choose the while loop method, so I renamed TrimUsingWhileLoop to Trim.

From the test below, you will see that the length of newString does not include whitespace characters, so the trim function worked.

 
<script type="text/javascript">
// I renamed the function TrimUsingWhileLoop to just Trim for short
function Trim(str)
{  while(str.charAt(0) == (" ") )
  {  str = str.substring(1);
  }
  while(str.charAt(str.length-1) == " " )
  {  str = str.substring(0,str.length-1);
  }
  return str;
}
 
// Here is how to use the new Trim function
 
var myString = " This is my string     ";
var newString = Trim(myString);
 
// The whitespace has been trimmed from the beginning and end of myString
// Let's use the string's built-in length function to test that
 
alert("myString length: " + myString.length);
alert("newString length: " + newString.length);
</script>
Last Updated ( Tuesday, 27 December 2005 )
 
< Prev   Next >