Is there a way that I can get the last value (based on the \'\\\' symbol) from a full path?
Example:
C:\\Documents and Settings\\img\\recycled log.jpg<
The following line of JavaScript code will give you the file name.
var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
alert(z);
A question asking "get file name without extension" refer to here but no solution for that. Here is the solution modified from Bobbie's solution.
var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];
<script type="text/javascript">
function test()
{
var path = "C:/es/h221.txt";
var pos =path.lastIndexOf( path.charAt( path.indexOf(":")+1) );
alert("pos=" + pos );
var filename = path.substring( pos+1);
alert( filename );
}
</script>
<form name="InputForm"
action="page2.asp"
method="post">
<P><input type="button" name="b1" value="test file button"
onClick="test()">
</form>
In Node.js, you can use Path's parse module...
var path = require('path');
var file = '/home/user/dir/file.txt';
var filename = path.parse(file).base;
//=> 'file.txt'
Another one
var filename = fullPath.split(/[\\\/]/).pop();
Here split have a regular expression with a character class
The two characters have to be escaped with '\'
Or use array to split
var filename = fullPath.split(['/','\\']).pop();
It would be the way to dynamically push more separators into an array, if needed.
If fullPath
is explicitly set by a string in your code it need to escape the backslash!
Like "C:\\Documents and Settings\\img\\recycled log.jpg"
I use:
var lastPart = path.replace(/\\$/,'').split('\\').pop();
It replaces the last \
so it also works with folders.