2

I have a script that grabs the filename from a URL but I have a problem.

Firstly, here's what I've got so far:

var img = $('img').attr('src'),
fileName_Index = img.lastIndexOf("/") + 1,
    fileName = img.substr(fileName_Index);

If the URL was to have ?format=foo after the filename, that part is added. Is there a way to remove the last part starting with the question mark leaving just the filename?

3
  • 2
    stackoverflow.com/questions/6560618/… Already asked Commented May 9, 2013 at 18:20
  • 1
    @Tezcat That question is about splitting up URLs in their entirety -- OP's needs are much more narrow and specific. Commented May 9, 2013 at 18:35
  • I agree with @Blazemonger, I've taken a look at that question although it seems very long winded for my needs. Commented May 9, 2013 at 18:39

1 Answer 1

2

Try adding this line to the end of your code sample:

fileName = fileName.replace(/[\#\?].*$/,''); // strips hashes, too

String.replace on MDN

Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly, thanks! Is there no way to shorten it, say fileName = img.substr(fileName_Index).replace(/[\#\?].*$/,'');? Just wondering :)
Sure can. I was just trying to keep my answer simple.

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.