4

I'm using JavaScript to try and get the filename from the URL.

I can get it using this:

var fn=window.location.href.match(/([^/])+/g);
alert(fn[fn.length-1]); // get the last element of the array

but is there an easier way to get it (e.g., without having to use fn[fn.length-1]

Thanks!!

6 Answers 6

4

Add a $ at the end so you only get the last part:

window.location.href.match(/[^/]+$/g);
Sign up to request clarification or add additional context in comments.

Comments

3

Personally, I try to use simple string manipulation for easy tasks like this. It makes for more readable code (for a person not very familiar with RegEx).

var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);

Or simply:

var filename = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1);

Additional Information

Not that it matters for something so trivial, but this method is also more performant than RegEx: http://jsperf.com/get-file-name

Comments

1

How about: window.location.href.match(/\/([^/]+)$/)[1];

Comments

0

you can use .pop() to get the last element of an array;

alert(fn.pop());

Comments

0

There is a jQuery plugin that makes it easy to parse URLs and provide access to their different parts. One of the things it does is return the filename. Here's the plugin on GitHub:

https://github.com/allmarkedup/jQuery-URL-Parser

I would recommend using that and avoid reinventing the wheel. Regular expressions is an area of programming where this is particularly applicable.

3 Comments

This seems like overkill to extract the file name from the URL.
If you're using jQuery anyway, and working with urls on a regular basis, I think the time you'll save outweighs the cons.
I can understand that point of view, but the OP doesn't even tag jQuery.
0

I recommend to also remove any '#' or '?' string, so my answer is:

var fn = window.location.href.split('/').pop().replace(/[\#\?].*$/,'');
alert(fn);

split('/').pop() removes the path
replace(/[\#\?].*$/,'') replace '#' or '?' until the end $ by empty string

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.