Converting characters into a URL friendly format

November 5th, 2010 posted by The Hippy

There is a handy command in Actionscript that I’d previously never encountered until this week:

escape()

If you’re receiving a text input and needing to send it out to a URL, for example in a search box, you need to convert any special characters into character codes before you request the URL. For example, a space should be sent as %20.

The escape() command allows you to do this with one command rather than having to search through character by character and reference it to a character codes array.

Here’s a simple function that utilises it:

public function processSearchTerm(s:String):void
{
var URLString:String = escape(s);
_rModel.searchTerm = URLString;
}

Calling this function, eg:

var oldString:String = "a test string";
var newString:String = processSearchTerm(testString);
trace(newString);

Should return:

a%20test%20string

Hopefully if you weren’t aware of it already, it will save you as much time as it did me!

Post to Twitter Post to Facebook Post to StumbleUpon Post to Digg