Spooky Case of the Wem Ghost
Installing Proprietary nVidia Drivers on Ubuntu Linux
Reading Email with PHP and IMAP/POP3
Garmin Edge 205 GPS Cycle Training Tool
Nasa's Space Shuttle Atlantis Transiting the Sun
Javascript Snippets

Javascript Snippets

Fri 05 Sep 2008
10:13AM
compton

Trimming Whitespace with Javascript

Here is a quick Javascript trim() function. Pass text to the function and it returns the text with leading and trailing whitespace removed. Spaces, tabs, and line-breaks before and after the text are stripped out. Click the HTML View button in the top-right corner of the code view below to try it out:

HTML View<script> <!-- function trim(text) { for (var first_nonwhite = 0; first_nonwhite < text.length && (text[first_nonwhite] == ' ' || text[first_nonwhite] == '\t' || text[first_nonwhite] == '\n' || text[first_nonwhite] == '\r'); first_nonwhite++); for (last_nonwhite = text.length-1; last_nonwhite > first_nonwhite && (text[last_nonwhite] == ' ' || text[last_nonwhite] == '\t' || text[last_nonwhite] == '\n' || text[last_nonwhite] == '\r'); last_nonwhite--); return text.substring(first_nonwhite, last_nonwhite+1); } --> </script> <textarea id="textarea" rows="10" cols="70"> Enter some text containing whitespace into this box. Click the button and only whitespace at the end and the beginning will be stripped. </textarea> <input type="button" onclick="document.getElementById('textarea').value = trim(document.getElementById('textarea').value);" value="trim" />
Code View

The key elements of the function are two 'empty' for loops. The two loops contain no code and their purpose is simply to locate the first non-whitespace character and the last, respectively. The first loop loops while the character pointed at by first_nonwhite is one of the whitespace characters. It starts at the beginning, and advances one character at a time up to the end or the first non-white character.

The second loop does a very similar thing, but this time looking for the last character of text which is non-white. To do this it starts at the end, and moves one character at a time towards the beginning, stopping at the first non-white. If no non-white characters were found by the first loop, this second loop won't do anything.

The text we want to return is everything that falls between the first non-whitespace character and the last. We get this using the substring(i, j) method, which returns the string between the ith and the jth character. (There's a similar method called substr(i, j), which returns the string which starts at the ith character and is j characters in length.)
 
Leave Comment