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
  • 24,767
  • 68
  • 217
  • 387

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
  • 29,356
  • 21
  • 76
  • 127
  • 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
  • 78,589
  • 36
  • 144
  • 183
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
  • 761,203
  • 64
  • 569
  • 643