Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中提取当前文档路径的URL的文件名?_Javascript_Jquery_Regex - Fatal编程技术网

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

如何在JavaScript中提取当前文档路径的URL的文件名?,javascript,jquery,regex,Javascript,Jquery,Regex,我正在尝试在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. 确定之前

我正在尝试在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();
这:

将为您提供如下信息:

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

然后,
.split()
会将字符串分割成一个数组,
.pop()
会给您数组中的最后一项。

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

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

在包含2到4个字母字符的句号(
[a-zA-Z]{2,4}
)之前,找到任意数量的字母数字或hypens
[a-zA-Z\-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\code>)或问号(

测试日期:

("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);
试试这个:

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

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

这个经过测试的正则表达式实现了以下功能:

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

有一个库,使使用URL非常容易。我推荐它

示例

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

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

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

filename => "img.png"

哇,你需要学习一些javascript
$(location.attr('href')
=
location.href
javascript是jQuery的前身,而不是aroundI在这里回答类似问题的另一种方式@Kei:I编辑标题是为了反映您只询问当前路径。我希望没关系。这真是太好了!谢谢@npe你错了<代码>位置。路径名
不返回查询/哈希参数。例如
http://somehost:8080/web/path/to/yourfile.txt?something=1222&another=more#andAHash
是您的
location.href
然后
location.pathname
返回
'/web/path/to/yourfile.txt'
请注意,这个答案解决了询问者的利基案例,但不支持所有有效的URL。我喜欢你没有直接回答OP的问题。答案是好的,如果你需要调动你的大脑,而不是像大多数情况下那样复制粘贴,那么可能更容易坚持+1你不是真的为此推荐图书馆吧?那太过分了。
filename => "img.png"