admin管理员组文章数量:1431231
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);
本文标签: javascriptRemoving data before the last forward slash in a stringStack Overflow
版权声明:本文标题:javascript - Removing data before the last forward slash in a string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745503555a2661142.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论