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.
#1 by Nikos on September 28, 2009 - 4:12 pm
Quote
awesome thanks
#2 by majk0 on February 23, 2010 - 12:20 pm
Quote
helped me a lot! thanks
#3 by Ferrol on March 30, 2010 - 9:09 am
Quote
Other internet examples are not workable because part of the RegExp expression is interpreted as comment. This is excellent, thanks for sharing!
#4 by John on July 2, 2010 - 10:26 am
Quote
how do you do it the other way around ? ie. replace backslash with forward slash
#5 by Nicholas on August 3, 2010 - 10:21 pm
Quote
Sorry it’s taken so long to respond; I’ve been kind of absent (read: work projects got BUSY).
I didn’t actually try it, but it should work just to change the escaped slashes.
Example:
var pattern:RegExp = /(\)/g;
var fixed: String = path.replace(pattern, “/”);
#6 by Erick on August 20, 2011 - 10:36 am
Quote
Hi,
It was not works in my example.
———————-
var path:String = “C: opdeeperkeepgoing.xml”;
var pattern:RegExp = /()/g;
var fixed: String = path.replace(pattern, “/”);
trace(fixed) C:opdeeperkeepgoing.xml
What could be wrong?
Thanks!Thanks!
#7 by ziro on August 4, 2010 - 3:01 am
Quote
nice work! thanks
#8 by molly h on July 3, 2011 - 3:58 pm
Quote
thanks for making a website for us people who dont know how to do stuff like this.
#9 by shawn on July 24, 2011 - 1:26 pm
Quote
heeeeeeeeey thank you so much!