Tip: Replacing Backslashes In AS3

I was just working on a project where I had to replace a backslash in a file path because I was using Zinc to output files on Windows (BLAH!). Anyway, Windows likes its file paths to look like this (C:\) instead of the normal (C:). Therefore you have to do some string manipulation if you want to save the file out properly.

My first guess was to use the String.replace() method and do the following:

Actionscript:
  1. path.replace("", "\");

That should work, and does work with everything other than backslashes. You see, backslashes are used to escape special characters in a string. What you have to do is actually use a Regular Expression here to take care of the double backslash problem. I wrote a method (actually converted one that I found on the net when searching about this topic) to do such a thing and put it in my StringUtils class.

Actionscript:
  1. /**
  2. * Uses Regular Expressions to replace backslashes in the provided string.
  3. *
  4. * @param $string The string to replace slashes in
  5. *
  6. * @return String
  7. */
  8. public static function replaceBackslashes($string:String):String
  9. {
  10.     return $string.replace(/\/g, "\\");
  11. }

Now you can just call the method and pass it in a String and you will get back the escaped String that you need.

Actionscript:
  1. trace(StringUtils.replaceBackslashes("this is \ the way to do it"));
  2. // this is \ the way to do it

Now, you may be asking yourself, what the hell just happened? It just traced out exactly what you put as part of the string. That is true but behind the scenes here is what is happening. If you traced out the following, you'd see the issue:

Actionscript:
  1. trace(StringUtils.replaceBackslashes("this is  the way to do it"));
  2. // this is  the way to do it

As you see there, the backslash in the string gets removed and all you see is the spaces around it. Because the backslash is a special character (as stated above) it needs to be escaped by using another backslash (\) for it to be usable and visible in a String. We then run it through the replaceBackslashes() method to apply the second backslash (if we want to show two) as shown in the previous example. Escaping characters inside of Strings in Flash is a bit tricky but as long as you remember which characters need to be escaped you should be good to go.

If you found this post useful, please consider leaving a comment, subscribing to the feed, or making a small donation.

1 Comment

You could have just used: replace('\\', '');

Leave a comment

(required)

(required)