Get the name of the Image in the URL

6

I need to get the image name in the url.

/data/data/com.intel.appx.IZICondominios.xwalk15/files/_pictures/picture_006.jpg

I need you to come back:

  

picture_006.jpg

The URL template is not fixed, every situation can change. You can have more or fewer folders.

    
asked by anonymous 19.12.2015 / 17:50

3 answers

2

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:

  • with regex

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]);
  • with split

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);
    
21.12.2015 / 02:53
4

An example using method lastIndexOf()

url = '/data/data/com.intel.appx.IZICondominios.xwalk15/files/_pictures/picture_006.jpg';
var filename = url.substring(url.lastIndexOf('/')+1);
console.log(filename);
    
21.12.2015 / 03:49
3

If your image name always has the same number of characters, you can do this:

var url = "/data/data/com.intel.appx.IZICondominios.xwalk15/files/_pictures/picture_006.jpg";

document.write(url.substring(url.length-15, url.length));

But if you have the same number of characters as the rest of your url, you can do this:

   var url = "/data/data/com.intel.appx.IZICondominios.xwalk15/files/_pictures/picture_006.jpg";

document.write(url.substring(65, url.length));

But if both are fickle:

var url = "/data/data/com.intel.appx.IZICondominios.xwalk15/files/_pictures/picture_006.jpg";
var n;
for(var i = url.length; i > 0; i--){
	if(url.charAt(i) == "/"){
  	n = i;
		break;
	}
}

document.write(url.substring(n+1, url.length));
    
19.12.2015 / 17:58