A certain variable might contain a relative path or an absolute path. Either way, I need to be able to pull the filename from the variable:
The directory structure is also arbitrary. So basically given either of the url's above (with arbirtrary directory structure) I need to pull 'filename.gif'. Thanks in advance
var filename = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
I'd use a regular expression.
It selects everything after the last slash until the end. You can expand it to select the extension separately:
var URL = window.location.pathname; // Gets page name var page = URL.substring(URL.lastIndexOf('/') + 1); alert(page);
For your examples, substring searching will probably be your best option.
However, if your URIs are actually complex enough, you might try Steven Levithan's
It has 2 modes and each has its share of quirks, so be sure to check out the demo.
// Extract filename from current page. var filePath = window.location.pathname; var fileName = filePath.substr(urlPath.lastIndexOf("/") + 1);
thanks sam deng, seems to work but you have a typo my friend:
// Extract filename from current page. var filePath = window.location.pathname; var fileName = filePath.substr(filePath.lastIndexOf("/") + 1);
var pathnameArray = window.location.pathname.split("/"); var nameOfFile = pathnameArray[pathnameArray.length -1];
There's probably some overhead I don't know about when considering making an array versus using the substr others have mentioned. So maybe this isn't a great answer but rather a different approach to solving the same problem.
If you url is like this:
and you want to just pull filename (/app_dev.php) so that you can link to your homepage use this:
var filename = window.location.pathname.substr(0, window.location.pathname.indexOf("/", 1)); window.location = filename;
var index = yourstring.lastIndexOf("/") + 1; var filename = yourstring.substr(index);
var filename = url.match(/.*\/(.*)$/);
var filename= url.split('/').pop()
var path = window.location.pathname; var filename = path.match(/.*\/([^/]+)\.([^?]+)/i);
Use this in the case that you don't want your query string to be part of your filename (which you probably don't).
I solved this problem by this:
var URL = window.location.pathname; // Gets page name var page = URL.substring(URL.lastIndexOf('/') + 1); // then display your filename to console console.info(page)
Use a regular expression, something along these lines should do the trick:
Although that doesn't cover every possible case, it should be more than suitable for most cases. You can these use:
var url = window.location.href; var regex = new RegExp("[^/]+\.[^/]+"); var fileName = regex.exec(url);
Hope that helps
var filename = /[^\\\/:*?"<>|\r\n]+$/i.exec(window.location.href);
©2020 All rights reserved.