This problem has two parts:
- read url
- extract the file name
read the url:
If you do not 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 the 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 contains .jpg
. You can do it like this ( example ):
/([^\/\]+.jpg)/
Using .split
simply remove the last element from the array that split
generates by breaking the string with str.split(/[\/\]/)
.
Examples:
Example that logs in the console if it does not find ...
var url = location.pathname;
var match = url.match(/[^\/\]+.jpg/);
if (!match) console.log('não encontrou...');
else alert(match[0]);
Example that logs in the console if it does not find ...
var url = location.pathname;
var partes = url.split(/[\/\]/);
var img = partes.pop();
if (!img) console.log('não encontrou...');
else alert(img);