views:

80

answers:

4

I need to extract the full path to a file using regExp

mydomain.com/path/to/file/myfile.html -> mydomain.com/path/to/file/

/mypath/file.txt -> /mypath/

anyone?

+1  A: 

Try this:

"mydomain.com/path/to/file/myfile.html".replace(/[^\/]*$/, "")
"/path/file.txt".replace(/[^\/]*$/, "")

But you can also do it without regular expressions by splitting:

"mydomain.com/path/to/file/myfile.html".split("/").slice(0, -1).join("/")+"/"
"/path/file.txt".split("/").slice(0, -1).join("/")+"/"
Gumbo
A: 

This works:

var file="mydomain.com/path/to/file/myfile.html";    
var match=/^(.*?)[\w\d\.]+$/g.exec(file);
var path=match[1];
mck89
A: 

This regex should do:

^(?:[^\/]*\/)*
Lucero
A: 

Should be faster without RegExp:

path.substr(0, path.lastIndexOf('/') + 1);

Examples:

var path = "mydomain.com/path/to/file/myfile.html";
path.substr(0, path.lastIndexOf('/') + 1);
"mydomain.com/path/to/file/"

var path = "/mypath/file.txt";
path.substr(0, path.lastIndexOf('/') + 1);
"/mypath/"

var path = "file.txt";
path.substr(0, path.lastIndexOf('/') + 1);
""
Vjeux