如何在JavaScript中提取当前文档路径的URL的文件名

How to extract the filename of the URL of the current document path in JavaScript?

本文关键字:路径 文档 URL 文件名 JavaScript 提取      更新时间:2023-09-26

我试图在没有任何参数的情况下提取Javascript中的当前文件名。

$(location).attr('href').match(/([a-zA-Z'-'_0-9]+'.'w+)$/);
var current_path = RegExp.$1;
if ((current_path == 'index.html') || ...) {
  // something here
}

但当你访问时,它根本不起作用http://example.com/index.html?lang=ja。在文件名将被随机更改之前,请确定。

知道吗?

如果您正在寻找路径中的最后一项,请尝试以下操作:

var current_path = window.location.pathname.split('/').pop();

此:

window.location.pathname

会给你这样的东西:

"/questions/6543242/how-to-extract-the-filename-of-url-in-javascript"

然后.split()会将字符串拆分为一个数组,.pop()会为您提供数组中的最后一项。

function filename(path){
    path = path.substring(path.lastIndexOf("/")+ 1);
    return (path.match(/[^.]+('.[^?#]+)?/) || [])[0];
}
console.log(filename('http://example.com/index.html?lang=ja'));
// returned value: 'index.html'

URL的文件名是最后一个"/"之后的所有内容,直到以下内容之一:1.("?"(URL查询的开头(,或2.("#"(URL片段开始(,或3.(字符串的结尾(如果没有查询或片段(。

这个经过测试的正则表达式做到了:

.match(/[^'/?#]+(?=$|[?#])/);

有一个URL.js库,可以很容易地使用URL。我推荐它!

示例

var uri = new URI('http://example.org/foo/hello.html?foo=bar');
uri.filename(); // => 'hello.html'

您的正则表达式不正确。相反,尝试更具体:

.match(/([a-zA-Z'-'_0-9]+'.[a-zA-Z]{2,4})['?'$]/);

说:

在句号之前找到任意数量的字母数字或hypens [a-zA-Z'-'_0-9]+,该句号具有2到4个字母字符[a-zA-Z]{2,4},该字母字符组合在末尾('$(或问号('?(之前

测试日期:

("http://www.example.com/index.html?lang=ja").match(/([a-zA-Z'-'_0-9]+'.[a-zA-Z]{2,4})['?'$]/);
var current_path = RegExp.$1;
alert(current_path);

试试这个:

window.location.pathname.substring(1)

您可以做一些更简单的事情:

var url = "http://google.com/img.png?arg=value#div5"
var filename = url.split('/').pop().split('#')[0].split('?')[0];

结果:

filename => "img.png"