A buddy of mine asked me the other day how to flip all of the forward slashes in a file path to backslashes using string replace() method in AS3. He said he couldn’t find the answer anywhere online, so I guess I’ll put it here so it will hopefully help someone.
var path:String = "/top/deeper/keep/going/"; var pattern:RegExp = /(\/)/g; var fixed:String = path.replace(pattern, "\\");
If you care to read an explanation of what’s going on, here we go.
Line 1: This is our string that we want to fix.
Line 2: This is our regex pattern that will grab the forward slashes. I think the part about this that may have been difficult is that you have to wrap your escaped forward slash in parentheses, or ActionScript thinks you’re trying to start a comment when you close your pattern with the next forward slash. The ‘g’ means that we want this pattern to be applied globally when we use it, and not just on the first match.
Line 3: This is where we use the pattern to find and replace all of the forward slashes with backslashes (escaped, of course).
That’s it. Pretty simple once you know how.