0

Given /foo/bar/image.jpg?x=1&y=2, how do I obtain image.jpg?

https://stackoverflow.com/a/423385 provides a partial answer, but does not address the GET parameters.

Community
  • 1
  • 1
user1032531
  • 22,993
  • 61
  • 191
  • 346

4 Answers4

4

You can use regex as others have suggested, but I find this more readable:

var src = '/foo/bar/image.jpg?x=1&y=2';
var img = src.split('/').pop().split('?')[0];
console.log(img);
Majid Fouladpour
  • 27,709
  • 19
  • 72
  • 126
  • All answers work, and I can't tell which one is best, but this one is a couple of characters shorter than the rest and maybe more readable (at least for a regex hack like me!). – user1032531 Oct 04 '15 at 16:02
2

Since the ? symbol separates the GET parameters from the URL, you can

str=str.split("?")[0]
filename = str.replace(/^.*[\/]/, '')
ProfFan
  • 178
  • 1
  • 8
1

Try:

var str = "/foo/bar/image.jpg?x=1&y=2";
var fileName = str.split('/').slice(-1)[0].split('?')[0];

or, for a regex method:

var fileName = str.split('/').slice(-1)[0].match(/[^?]+/)[0];
hjpotter92
  • 75,209
  • 33
  • 136
  • 171
1

You can use this regex:

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

and use captured grpup #1.

RegEx Demo

/        # matches a literal /
[^?\/]+  # matches 1 or more of any char that is not ? or /
(?=\?|$) # is a lookahead to assert that next position is ? or end of line
anubhava
  • 713,503
  • 59
  • 514
  • 593