Get filename from URL using Javascript

http://befused.com/javascript/get-filename-url

Get filename from URL using Javascript

 

This snippet will get the filename from the url. The filename is the last part of the URL from the last trailing slash. For example, if the URL is http://www.example.com/dir/file.html then
file.html is the file name.

Explanation

  1. var url = window.location.pathname;

This declares the url variable and adds the current pathname as its value.

  1. var filename = url.substring(url.lastIndexOf('/')+1);
  2. alert(filename);

substring (method) - extract characters from start (parameter).
url is the stringObject url.substring(start)

lastIndexOf (method) - position of last occurrence of specified string value, in this case the '/'

Add one to lastIndexOf because we do not want to return the '/'

Full snippet

  1. var url = window.location.pathname;
  2. var filename = url.substring(url.lastIndexOf('/')+1);
  3. alert(filename);

 

 

Other question:

https://stackoverflow.com/questions/423376/how-to-get-the-file-name-from-a-full-path-using-javascript

https://stackoverflow.com/questions/680929/how-to-extract-extension-from-filename-string-in-javascript

 

posted @ 2017-08-01 17:04  任国强  阅读(766)  评论(0编辑  收藏  举报