-1

Problem:

Extract image file name from CDN address similar to the following:

https://cdnstorage.api.com/v0/b/my-app.com/o/photo%2FB%_2.jpeg?alt=media&token=4e32-a1a2-c48e6c91a2ba

Two-stage Solution:

I am using two regular expressions to retrieve the file name:

var postLastSlashRegEx = /[^\/]+$/,
    preQueryRegEx = /^([^?]+)/;

var fileFromURL =  urlString.match(postLastSlashRegEx)[0].match(preQueryRegEx)[0];

// fileFromURL = "photo%2FB%_2.jpeg"

Question:

Is there a way I can combine both regular expressions?

I've tried using capture groups, but haven't been able to produce a working solution.

Lindauson
  • 2,963
  • 1
  • 30
  • 33

3 Answers3

1

From my comment

You can use a lookahead to find the "?" and use [^/] to match any non-slash characters.

/[^/]+(?=\?)/

To remove the dependency on the URL needing a "?", you can make the lookahead match a question mark or the end of line indicator (represented by $), but make sure the first glob is non-greedy.

/[^/]+?(?=\?|$)/

Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
0

You don't have to use regex, you can just use split and substr.

var str = "https://cdnstorage.api.com/v0/b/my-app.com/o/photo%2FB%_2.jpeg?alt=media&token=4e32-a1a2-c48e6c91a2ba".split("?")[0];
var fileName = temp.substr(temp.lastIndexOf('/')+1);

but if regex is important to you, then:

str.match(/[^?]*\/([^?]+)/)[1]
Sahar Zehavi
  • 580
  • 6
  • 16
0

The code using the substring method would look like the following -

var fileFromURL = urlString.substring(urlString.lastIndexOf('/') + 1, urlString.lastIndexOf('?'))

Atty
  • 691
  • 13
  • 20
  • Thanks for your response, @Atty. I knew I could use string functions but I wanted to see what a pure regex solution would look like. – Lindauson Apr 19 '17 at 14:40