简体   繁体   中英

Use Regex in Javascript to get the filename in a URL

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 (eg, without having to use fn[fn.length-1]

Thanks!!

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

最后添加一个$ ,这样你才能得到最后一部分:

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

怎么样: window.location.href.match(/\\/([^/]+)$/)[1];

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

你可以使用.pop()来获取数组的最后一个元素;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM