-3

 var URLS = ['https://www.vsss.co.in/Admin/uploads/722661/bb.jpg','https://www.vsss.co.in/Admin/uploads/755153/scs.jpg','https://www.vsss.co.in/Admin/uploads/704543/1606.jpg']
URLS.forEach(function(element){
    var image_name = element.replace("https://www.vsss.co.in/Admin/uploads/722661/", "");
    console.log(image_name);
});  

Anyone can please help me How can I get image name and extension of the image from URL. I tried but I statically typed URL when 722661 is dynamically generated serial How can I solve this issue?

shah rushabh
  • 155
  • 1
  • 1
  • 8
  • var image_name =element.split('/')[element.length] – M14 Jun 04 '18 at 10:42
  • I particularly like [this answer](https://stackoverflow.com/a/36756650/511529) of the question I linked to, because it also takes url parameters and hash tags into account, so it's a very flexible, reusable solution. – GolezTrol Jun 04 '18 at 10:43

3 Answers3

4

Take the substring starting from the last / + 1. Using string functions here is much faster than any array creation methods / replacements.

const URLS = ['https://www.vsss.co.in/Admin/uploads/722661/bb.jpg','https://www.vsss.co.in/Admin/uploads/755153/scs.jpg','https://www.vsss.co.in/Admin/uploads/704543/1606.jpg'];

function getFileName(s) {
 return s.substring(s.lastIndexOf('/') + 1);
}

const fileNames = URLS.map(getFileName);
console.log(fileNames);

Performance: https://jsperf.com/string-function-array/1

baao
  • 71,625
  • 17
  • 143
  • 203
0

You can split the url based on / and get the last value

var URLS = ['https://www.vsss.co.in/Admin/uploads/722661/bb.jpg','https://www.vsss.co.in/Admin/uploads/755153/scs.jpg','https://www.vsss.co.in/Admin/uploads/704543/1606.jpg']
URLS.forEach(function(element){
    var image_name = element.split("/").pop();
    console.log(image_name.split('.'));
});
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • 1
    This is not a performant solution. Using string functions is approx 2 times faster – baao Jun 04 '18 at 10:47
  • you could employ lastIndexOf("/") as well, never the less but the solution is very interesting!!! – Victor Dec 20 '18 at 17:43
-1

You can do this with Regex. Try this regex:

/[\w-]+\.jpg/g

And to support more file extensions:

/[\w-]+\.(jpg|png|gif)/g

Example:

var URLS = [ 'https://www.vsss.co.in/Admin/uploads/722661/bb.jpg', 'https://www.vsss.co.in/Admin/uploads/755153/scs.jpg', 'https://www.vsss.co.in/Admin/uploads/704543/1606.jpg' ];

URLS.forEach( function ( element ) {
    var image_name = element.match( /[\w-]+\.jpg/g );
    console.log( image_name.join() );
} );
Kavian K.
  • 1,340
  • 1
  • 9
  • 11