admin管理员组

文章数量:1316658

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!!

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!!

Share Improve this question edited Nov 3, 2011 at 12:17 codaddict 455k83 gold badges499 silver badges536 bronze badges asked Nov 3, 2011 at 12:16 user815460user815460 1,1433 gold badges11 silver badges17 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 4

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

window.location.href.match(/[^/]+$/g);

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./get-file-name

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

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

alert(fn.pop());

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./allmarkedup/jQuery-URL-Parser

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

I remend 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

本文标签: Use Regex in Javascript to get the filename in a URLStack Overflow