Removing Spaces from a String in ActionScript 3

by Kevin Partner on 29th January, 2009

Here’s a simple, two line function for removing spaces (can be adapted for any other character) from a string in AS3. I used it for removing any spaces typed into a Post Code.

public function stripspaces(originalstring:String):String
{
var original:Array=originalstring.split(” “);
return(original.join(“”));
}

All we’re doing is splitting the array using the space character and then joining that array back together into a string with no delimiter, thus eliminating the space.

Share and Enjoy:
  • Print
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Technorati
  • Add to favorites

{ 11 comments… read them below or add one }

Shaedo May 10, 2009 at 6:50 pm

Nice! Thanks for taking the time to write this and make it available!

Shaedo May 10, 2009 at 6:57 pm

be aware that when copying and pasting this code you will probably have to redo the ” as they go a bit funny due to the copy/paste

Michael Lindvall May 21, 2009 at 8:51 pm

Thanks. This worked like a charm.

Ian July 15, 2009 at 2:10 am

Very useful. Thank you very much!

James Womack July 22, 2009 at 10:43 pm

I modified this to convert spaces to URL-encoded spaces (%20). Thanks for the help!

O L September 17, 2009 at 2:49 pm

Much simpler:
myString.replace(/\s+/g, ”));

dbj October 31, 2009 at 2:32 am

function strip(original, of_what )
{
return (original.split( of_what || ” “)).join(“”);
}

Probably a bit more useful …
Also the second, optional, argument can be either string or an regular expression …

–DBJ

dbj October 31, 2009 at 9:28 am

I defy any C# “afficionado” to show me parallel to this, in her favourite language ;o)

if (“function” !== typeof “”.minus)
String.prototype.minus = function( what_ ) {
///
/// “ABCBDBEB”.minus(“B”), returns : “ACDE”
/// Argument is optional, by default it is one space char
/// myText.minus(), returns myText without spaces
/// argument can be an regular expression
/// reg.exp. given does not require ‘g’ or ‘m’ modifier
/// if argument is not found in the original, the original is returned
///
return (this.split(what_ || ” ” )).join( “” ) ;
}

–DBJ

Dustin December 9, 2009 at 10:23 pm

Thanks!

dca January 19, 2010 at 8:32 pm

Thank you so much for the tutorial!!! It worked flawlessly! I modified it so that it removed extra vertical spaces in an external text document.

davet March 26, 2010 at 10:35 am

Hi

I don’t know if someone else has mentioned this but you can use stuff like:

var inString:String = ” this has whitespace”;
var inString2:String = “this has no whitespace”;

var a:Array = inString.split(/^\s+/);
var b:Array = inString2.split(/^\s+/);

Any leading whitespace is removed , you can use different flags to adapt to your needs
Nice post though

All the best

Leave a Comment

Previous post:

Next post: