I have a file location in a variable and all I need to do is get the value from the last /
onwards.
For example the contents of my variable (named myfile
) would look like /home/tony/files/test.pdf
or /tmp/admin.doc
. I just want to go to the end of the variable and go backwards until I get to a /
and then take the value from that point onwards.
Any ideas?
I have a file location in a variable and all I need to do is get the value from the last /
onwards.
For example the contents of my variable (named myfile
) would look like /home/tony/files/test.pdf
or /tmp/admin.doc
. I just want to go to the end of the variable and go backwards until I get to a /
and then take the value from that point onwards.
Any ideas?
Share Improve this question edited Feb 21, 2012 at 16:36 user142162 asked Feb 21, 2012 at 15:23 user1223680user1223680 31 silver badge2 bronze badges 1-
4
lastIndexOf('/')
is your friend – biziclop Commented Feb 21, 2012 at 15:24
4 Answers
Reset to default 6You can acplish this using String.substring()
and String.lastIndexOf()
:
var index = myfile.lastIndexOf('/');
if(index != -1)
{
var newStr = myfile.substring(index + 1);
}
Another method of doing this would be to use regular expressions:
var newStr = myfile.replace(/^.*\/(?=[^\/]*$)/, '');
var location = "/home/time/json.pdf";
var parts = location.split('/');
var index = parts.length-1;
alert(parts[index]);
this would do it, but with regex or substring I guess you could do this much faster.
if you write it like this, a file name without any directory path will be returned unchanged.
myfile.substring(myfile.lastIndexOf('/')+1);
with Regex
var filePath = '/home/tony/files/test.pdf';
var fileName = filePath.match(/[^\/]*$/);
document.write(fileName);
without Regex
var filePath = '/home/tony/files/test.pdf';
var fileName = filePath.split('/').pop();
document.write(fileName);