This problem has two parts:
- read the url
- extract file name
read the url:
If you don’t already have the url in a string you can use location.pathname
or even location.href
. This will give you a string that you can use in the next step
extract file name
You can do this with Regex or with .split
.
Using regex the rule you are looking for is a string that is at the end of the url (using location.pathname
) and containing .jpg
. You can do it like this (example):
/([^\/\\]+.jpg)/
Using .split
simply remove the last element from the array split
generates by breaking the string with str.split(/[\/\\]/)
.
Examples:
Example that logs to console if not found...
var url = location.pathname;
var match = url.match(/[^\/\\]+.jpg/);
if (!match) console.log('não encontrou...');
else alert(match[0]);
Example that logs to console if not found...
var url = location.pathname;
var partes = url.split(/[\/\\]/);
var img = partes.pop();
if (!img) console.log('não encontrou...');
else alert(img);
Solved my problem! Too bad that answer is last placed on the page. I tested all solutions until I get to that which is the simplest.
– Y. Menon