Apr 01
So I had a question about using my prototyped stripWhitespace function for Strings in AS3. Since it was written for actionscript 2 it has a few different problems when using it in AS3. First of all, variables are not typed at all, which is almost required in AS3. Next, it uses prototyping, which in AC3 should really only be used in very special circumstances. So I updated the function for use in AS3, using a utility class instead. Take a look.
package com.macsims.util
{
public final class StringUtils
{
public static function stripWhitespace(string:String, options:String = null):String
{
// default is to strip all
var result:String = string;
var resultArray:Array;
// convert tabs to spaces
if(options == null || options.indexOf("t",0) > -1)
result = result.split("\t").join(" ");
// convert returns to spaces
if(options == null || options.indexOf("r",0) > -1)
result = result.split("\r").join(" ");
// convert newlines to spaces
if(options == null || options.indexOf("n",0) > -1)
result = result.split("\n").join(" ");
// compress spaces
if(options == null || options.indexOf("s",0) > -1) {
resultArray = result.split(" ");
for(var idx:uint = 0; idx < resultArray.length; idx++)
{
if(resultArray[idx] == "")
{
resultArray.splice(idx,1);
idx--;
}
}
result = resultArray.join(" ");
}
return result;
}
}
}
and you would use it like this:
var myText:String = "This text has too many spaces."; var betterText:String = StringUtils.stripWhitespace(myText);
Enjoy!
August 10th, 2008 at 12:31 pm
To take this one step further, how would you turn
“My String”
into
“MyString” ?
Not following from your example on where to specify the distance between.
September 22nd, 2008 at 4:01 pm
Hey, just wanted to put in a plug that your function works like a charm!
I integrated it into my latest project within a couple of minutes. AS3 could stand to have a few more string processing functions built in. For now though, this function worked great. Thanks for sharing!
October 2nd, 2008 at 7:42 am
Just wanted to say thanks!
Also totally agree with Andrew that this kind of stuff should be built-in.
May 7th, 2009 at 2:20 pm
Thanks GREATLY! Spent a lot of time today looking for this answer!!