-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?

2
  • var image_name =element.split('/')[element.length] Commented Jun 4, 2018 at 10:42
  • I particularly like this answer 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. Commented Jun 4, 2018 at 10:43

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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('.'));
});

2 Comments

This is not a performant solution. Using string functions is approx 2 times faster
you could employ lastIndexOf("/") as well, never the less but the solution is very interesting!!!
-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() );
} );

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.