I just made my own version of this. My function can be used to extract whatever you want from it, if you don't need all of it, then you can easily remove some code.
<html>
<body>
<script type="text/javascript">
// Useful function to separate path name and extension from full path string
function pathToFile(str)
{
var nOffset = Math.max(0, Math.max(str.lastIndexOf('\\'), str.lastIndexOf('/')));
var eOffset = str.lastIndexOf('.');
if(eOffset < 0 && eOffset < nOffset)
{
eOffset = str.length;
}
return {isDirectory: eOffset === str.length, // Optionally: && nOffset+1 === str.length if trailing slash means dir, and otherwise always file
path: str.substring(0, nOffset),
name: str.substring(nOffset > 0 ? nOffset + 1 : nOffset, eOffset),
extension: str.substring(eOffset > 0 ? eOffset + 1 : eOffset, str.length)};
}
// Testing the function
var testcases = [
"C:\\blabla\\blaeobuaeu\\testcase1.jpeg",
"/tmp/blabla/testcase2.png",
"testcase3.htm",
"C:\\Testcase4", "/dir.with.dots/fileWithoutDots",
"/dir.with.dots/another.dir/"
];
for(var i=0;i<testcases.length;i++)
{
var file = pathToFile(testcases[i]);
document.write("- " + (file.isDirectory ? "Directory" : "File") + " with name '" + file.name + "' has extension: '" + file.extension + "' is in directory: '" + file.path + "'<br />");
}
</script>
</body>
</html>
Will output the following:
- File with name 'testcase1' has extension: 'jpeg' is in directory: 'C:\blabla\blaeobuaeu'
- File with name 'testcase2' has extension: 'png' is in directory: '/tmp/blabla'
- File with name 'testcase3' has extension: 'htm' is in directory: ''
- Directory with name 'Testcase4' has extension: '' is in directory: 'C:'
- Directory with name 'fileWithoutDots' has extension: '' is in directory: '/dir.with.dots'
- Directory with name '' has extension: '' is in directory: '/dir.with.dots/another.dir'
With && nOffset+1 === str.length
added to isDirectory
:
- File with name 'testcase1' has extension: 'jpeg' is in directory: 'C:\blabla\blaeobuaeu'
- File with name 'testcase2' has extension: 'png' is in directory: '/tmp/blabla'
- File with name 'testcase3' has extension: 'htm' is in directory: ''
- Directory with name 'Testcase4' has extension: '' is in directory: 'C:'
- Directory with name 'fileWithoutDots' has extension: '' is in directory: '/dir.with.dots'
- Directory with name '' has extension: '' is in directory: '/dir.with.dots/another.dir'
Given the testcases you can see this function works quite robustly compared to the other proposed methods here.
Note for newbies about the \\: \ is an escape character, for example \n means a newline and \t a tab. To make it possible to write \n, you must actually type \\n.