最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Removing data before the last forward slash in a string - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 6

You 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);

发布评论

评论列表(0)

  1. 暂无评论