在Javascript中使用Regex来获取URL中的文件名

Use Regex in Javascript to get the filename in a URL

本文关键字:获取 URL 文件名 Regex Javascript      更新时间:2023-09-26

我正在使用JavaScript尝试从URL获取文件名。

我可以用下面的命令得到它:

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

,但是否有更简单的方法来获得它(例如,不必使用fn[fn.length-1]

)

谢谢! !

在末尾添加一个$,这样您只会得到最后一部分:

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

就我个人而言,我尝试使用简单的字符串操作来完成这样的简单任务。它使代码更具可读性(对于不太熟悉RegEx的人来说)。

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

或简单的:

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

这并不重要,但这个方法也比RegEx性能更好:http://jsperf.com/get-file-name

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

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

alert(fn.pop());

有一个jQuery插件可以很容易地解析url并提供对其不同部分的访问。它所做的事情之一是返回文件名。下面是GitHub上的插件:

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

我建议使用它,避免重复发明轮子。正则表达式是一个特别适用于此的编程领域。

我建议也删除任何'#'或'?'字符串,所以我的答案是:

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

split('/').pop()移除路径
replace(/['#'?].*$/,'')替换'#'或'?