Strip Whitespace From String ActionScript 3.0
April 8th, 2009 | Published in ActionScript | by Jeremy | 3 Comments
Just came up with this simple method for removing extra whitespace from a string using regular expressions and the String.replace() method. Many examples found on the web involve looping through the entire string and evaluating individual characters which can be an expensive operation. Using regular expressions, as shown below, can definitely save some keystrokes and processing.
// -- String with tab, multiple spaces and newline char
var testString:String = 'here is a tabthere are six spaces here is a new linennext line';
// -- Test expression
var whitespace:RegExp = /(\t|\n|\s{2,})/g;
trace( 'testString pre-replace: ' + testString );
// -- Re-assign the value of testString to the result of replace() mehtod
testString = testString.replace( whitespace, ' ' );
trace( 'testString post-replace: ' + testString )
The replace() method turns all multiple spaces, tabs and newline characters into single spaces.

July 15th, 2009at 7:55 pm(#)
Looks a good approach. But the reg exp
var whitespace:RegExp = /(t|n|s{2,})/g;
is striping out ‘t’ ’s and ‘n’ ’s instead of tabs and newlines.
July 16th, 2009at 1:43 am(#)
Nice catch!
Looks like the back-slashes were stripped from the original post before I switched to using dp.SyntaxHighlighter. I’ve fixed the missing back-slashes in the code example. Should work like a charm now.
Thanks
December 7th, 2009at 1:39 am(#)
Jeremy, thanks man. This is exactly what I was looking for. Consider yourself a new member of my google reader RSS feeds.