A buddy of mine asked me the other day how to flip all of the for­ward slashes in a file path to back­slashes using string replace() method in AS3. He said he couldn’t find the answer any­where online, so I guess I’ll put it here so it will hope­fully 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 expla­na­tion 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 pat­tern that will grab the for­ward slashes. I think the part about this that may have been dif­fi­cult is that you have to wrap your escaped for­ward slash in paren­the­ses, or Action­Script thinks you’re try­ing to start a com­ment when you close your pat­tern with the next for­ward slash. The ‘g’ means that we want this pat­tern to be applied glob­ally when we use it, and not just on the first match.

Line 3: This is where we use the pat­tern to find and replace all of the for­ward slashes with back­slashes (escaped, of course).

That’s it. Pretty sim­ple once you know how.

Tags: , , , ,