javascript – How do I pull a file from a URL?

Question:

I found several answers on the Internet, but my case is not entirely standard, since in the path, in addition to the link to the file, additional attributes may appear, and the nesting may change. here is the link:

http://misite.ru/sites/default/files/styles/760_______/public/62242.jpg?itok=cQO_3H5R

I think the reliable way to extract a file from a string is as follows:

The file always ends with .jpg I somehow extract part of the line, from / (not including) to .jpg (inclusive), which will be my file 62242.jpg .

but I don’t know how to implement it with the code.

Answer:

Divide by / , take the last part.
Divide by ? , take the first element of the result.

In the absence of the ?query part, split will still return an array with one element.

[
'http://misite.ru/sites/default/files/styles/760_______/public/62242.jpg?itok=cQO_3H5R',
'http://misite.ru/sites/default/files/styles/760_______/public/62242.jpg',
].forEach(url => {
  console.log(url.split('/').pop().split('?')[0]);
})
Scroll to Top