I need to extract the full path to a file using regExp
mydomain.com/path/to开发者_StackOverflow中文版/file/myfile.html
-> mydomain.com/path/to/file/
/mypath/file.txt
-> /mypath/
anyone?
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);
""
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("/")+"/"
This regex should do:
^(?:[^\/]*\/)*
This works:
var file="mydomain.com/path/to/file/myfile.html";
var match=/^(.*?)[\w\d\.]+$/g.exec(file);
var path=match[1];
精彩评论