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?
-
2stackoverflow.com/questions/6560618/… Already askedLu Wang– Lu Wang2013年05月09日 18:20:12 +00:00Commented 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.Blazemonger– Blazemonger2013年05月09日 18:35:01 +00:00Commented 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.user2352358– user23523582013年05月09日 18:39:29 +00:00Commented May 9, 2013 at 18:39
1 Answer 1
Try adding this line to the end of your code sample:
fileName = fileName.replace(/[\#\?].*$/,''); // strips hashes, too
answered May 9, 2013 at 18:20
Blazemonger
93.3k28 gold badges147 silver badges181 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
user2352358
Works perfectly, thanks! Is there no way to shorten it, say
fileName = img.substr(fileName_Index).replace(/[\#\?].*$/,'');? Just wondering :)Blazemonger
Sure can. I was just trying to keep my answer simple.
lang-js