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.

7
  • you could use the information in the location object to get it. w3schools.com/jsref/obj_location.asp Commented Oct 4, 2015 at 15:41
  • @toskv /foo/bar/image.jpg?x=1&y=2 is the src of an image, and not the page URL. Does your recommendation still apply? Commented Oct 4, 2015 at 15:42
  • oh, that's right. :) Commented Oct 4, 2015 at 15:43
  • you can add up to this regex "fullPath.replace(/^.*[\\\/]/, '')" to avoid everything after the question mark as well. Commented Oct 4, 2015 at 15:44
  • @priyavyas jsfiddle.net/d8hepjxu? Commented Oct 4, 2015 at 15:46

4 Answers 4

7

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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!).
2

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

str=str.split("?")[0]
filename = str.replace(/^.*[\/]/, '')

Comments

2

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

2 Comments

Includes a leading forward-slash. Thanks for the explanation,however!
NO it doesn't include / in captured group. I wrote clearly use captured grpup #1 in my answer.
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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.