views:

2739

answers:

6

Does AS3 have a built in class / function to extract "filename" from a complete path. e.g. I wish to extract "filename.doc" from full path "C:\Documents and Settings\All Users\Desktop\filename.doc"

+2  A: 

Couldn't you just do something basic like:

string filename = filename.substring(filename.lastIndexOf("\\") + 1)

I know it's not a single function call, but it should work just the same.

Edited based on @Bryan Grezeszak's comment.

cmptrgeekken
The fullpath string is dynamically picked up when user selects a file and looks like "c:\temp\abc.doc" lastIndexOf("\\") dosen't work for above.
why not? lastIndexOf("\\") means find the last '\' and tell me its index in the string..
meandmycode
You're on the right path, but you need to add one to the index to remove the actual slash from the final result :)
Bryan Grezeszak
A: 

Apparently you can use the File class, or more specifically, the File.separator static member if you're working with AIR. It should return "/" or "\", which you can plug in to @cmptrgeekken's suggestion.

aib
A: 

This regex works with both the \ and / notation:

var filename:String = fullPath.match(/(?:\\|\/)([^\\\/]*)$/)[1];
Lillemanden
+1  A: 

First you want to find the last occurrence of / or \ in the path, do that using this:

var fSlash: int = fullPath.lastIndexOf("/");
var bSlash: int = fullPath.lastIndexOf("\\"); // reason for the double slash is just to escape the slash so it doesn't escape the quote!!!
var slashIndex: int = fSlash > bSlash ? fSlash : bSlash;

That will give you the index in the string that is right BEFORE that last slash. So then to return the portion of the string after that, you add one to the index (moving it past the last slash) and return the remainder of the string

var docName: String = fullPath.substr(slashIndex + 1);

To do this as a simple to use function, do this:

function getFileName(fullPath: String) : String
{
    var fSlash: int = fullPath.lastIndexOf("/");
    var bSlash: int = fullPath.lastIndexOf("\\"); // reason for the double slash is just to escape the slash so it doesn't escape the quote!!!
    var slashIndex: int = fSlash > bSlash ? fSlash : bSlash;
    return fullPath.substr(slashIndex + 1);
}

var fName: String = getFileName(myFullPath);
Bryan Grezeszak
Thanks for the code. However I have a dynamic path string which looks like "D:\temp\abc.doc". getFileName("D:\temp\abc.doc")returns "D:empabc.doc".
No you don't :) Backslashes act as escapes when you make a string, that's why \n makes a new line, \t makes a tab, etc. Your string of 'D:\temp\abc.doc' actually ends up as 'D:{tab}emp{symbol}bc.doc, you didn't actually make a string that contains any slashes unless you escape the slashes, like \\
Bryan Grezeszak
A: 

thanks! regex >= awesome

A: 

For Air, you can try using File Class to extract file name

var file:File=new File("path_string");   
//path_string example "C:\\Windows\\myfile.txt"  
var filename:String = file.name;
Amitd