I'm trying to remove the filename from a path created in C# (using Server.MapPath, which by default uses \\
), like :
C:\\Foo\\Bar\\Baz\\file.js
My current regex looks to be somewhat working in RegExr but in the real application it works just the opposite way :
\/[^\\]+$
What am I missing ?
I'm trying to remove the filename from a path created in C# (using Server.MapPath, which by default uses \\
), like :
C:\\Foo\\Bar\\Baz\\file.js
My current regex looks to be somewhat working in RegExr but in the real application it works just the opposite way :
\/[^\\]+$
What am I missing ?
Share Improve this question edited Dec 31, 2012 at 5:08 Derek 朕會功夫 94.5k45 gold badges198 silver badges253 bronze badges asked Dec 31, 2012 at 4:10 mike_hornbeckmike_hornbeck 1,6223 gold badges30 silver badges52 bronze badges 1- 1 Try tagging the question correctly. – ocodo Commented Dec 31, 2012 at 4:19
4 Answers
Reset to default 5Since you're doing this in JS just do a String.split
operation.
var path = "C:\\Foo\\Bar\\Baz\\file.js";
var separator = "\\";
function getFilenameFromPath(path, separator){
var segmented = path.split(separator);
return segmented[segmented.length-1];
}
console.log(getFilename(path, separator));
The RegEx way...
By the way, the only thing wrong with your original RegEx was the leading \ and the missing /
/[^\\]+$/
Would nails it. (the trailing /g
on @JDwyers answer is to make it a global match, that's
redundant for your use case.)
So...
path.match(/[^\\]+$/); // == "file.js"
Cheers
to keep with your regex:
var s = "C:\\Foo\\Bar\\Baz\\file.js";
var fileName = s.match(/[^\\]+$/g);
Since you want the directory path, by removing the file name, thus:
var path = "C:\\Foo\\Bar\\Baz\\file.js";
var separator = "\\"; // make it OS agnostic.
var result="";
function getFilename(path, separator){
var segmented = path.split(separator);
for(var i=0; i<segmented.length-1;i++)
{
result+=segmented[i]+"\\\\";
}
return result;
}
alert(getFilename(path, separator));
Why are you using Regular Expressions for this? It is overkill when there is a function provided to do this in the Path
class:
string dirName = Path.GetDirectoryName(filename);
There are also similar functions in the Path class to extract the filename, the extension, the path root, etc.