How can one remove whitespace from a string in as3?
I would like to be able to remove all carriage returns, spaces, tabs etc.
Tested and works on AnimateCC for iOS air app:
// Regular expressions
var spaces:RegExp = / /gi; // match "spaces" in a string
var dashes:RegExp = /-/gi; // match "dashes" in a string
// Sample string with spaces and dashes
loginMC.userName.text = loginMC.userName.text.replace(spaces, ""); // find and replace "spaces"
loginMC.userName.text = loginMC.userName.text.replace(dashes, ":"); // find and replace "dashes"
trace(loginMC.userName.text);
You can use RegExp.
var rex:RegExp = /[\s\r\n]+/gim;
var str:String = "This is a string.";
str = str.replace(rex,'');
// str is now "Thisisastring."
For trimming front and back of strings, use
var rex:RegExp /^\s*|\s*$/gim;
If you have access to the AS3 Flex libraries, there's StringUtil.trim(" my string ")
too. See here for the docs.
It doesn't do exactly what the OP was after, but as this was the top answer on google for AS3 String trimming, I thought it'd be worth posting this solution for the more usual Stringy trimmy requirement.
The simplest way of removing not only spaces but any char for that matter, is as follows,
//Tested on Flash CS5 and AIR 2.0
//Regular expressions
var spaces:RegExp = / /gi; // match "spaces" in a string
var dashes:RegExp = /-/gi; // match "dashes" in a string
//Sample string with spaces and dashes
var str:String = "Bu s ~ Tim e - 2-50-00";
str = str.replace(spaces, ""); // find and replace "spaces"
str = str.replace(dashes, ":"); // find and replace "dashes"
trace(str); // output: Bus~Time:2:50:00