I found several answers on the Internet, but my case is not quite standard, since along with the link to the file, additional attributes may appear, and nesting can also change. here is the link:

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

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

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

but I do not know how to implement this code.

  • File - rarely ends in .jpg , do you mean the file name? - vp_arth
  • one
    url.split('/').pop().split('?')[0] ? - vp_arth
  • did not quite understand you)) but what part of the line I need to extract I showed) - Evgeny Shevtsov
  • When I need to вытащить файл из урл , I execute the http request) So it’s clearer? - vp_arth
  • yes no, I don’t need to fulfill the http request just to extract the necessary part from the line) - Evgeny Shevtsov

2 answers 2

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

If there is no ?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]); }) 

     var pos1 = pathstr.lastIndexOf("/"); var pos2 = pathstr.lastIndexOf(".jpg"); var filename = ""; if ( ( pos1 >= 0 ) && ( pos2 > 0 ) && ( pos2 > pos1 ) ) { filename = pathstr.substring(pos1+1,pos2+3); }