Remove spaces

September 24th, 2009

Busy busy busy…. I’ve been too busy to blog for longer than I can remember.

I’ve got loads of stuff to post, but it needs a bit of cleaning up first (as most of it suffered late night last-minute hacks to accommodate client changes).

But anyway, here’s a simple little String function that removes any spaces from the start or end of a String, and removes any multiple spaces from within a String.

For example:

Input: "     Hello   world        "
Output: "Hello world" 

Here’s the code (Flash AS3):

function removeSpaces(string:String):String{

	//remove spaces at start
	while(string.substr(0,1) == " "){
		string = string.substring(1);
	}
	//remove multiple spaces in middle
	while(string.indexOf("  ") != -1){
		string = string.split("  ").join(" ");
	}
	while(string.substr(-1) == " "){
		string = string.substr(0,string.length-1);
	}
	return string;
}

Might save you five minutes!

Leave a Reply