如何在JavaScript中提取当前文档路径的URL的文件名? [英] How to extract the filename of the URL of the current document path in JavaScript?

查看:89
本文介绍了如何在JavaScript中提取当前文档路径的URL的文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to extract the current file name in Javascript without any parameters.

$(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 时,它根本不起作用。当然,文件名将随机更改。

But it doesn't work at all when you access like http://example.com/index.html?lang=ja. Sure before the file name will be changed at random.

任何想法?

推荐答案

如果你正在寻找路径中的最后一项,试试这个:

If you're looking for the last item in the path, try this:

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

这个:

window.location.pathname

会给你类似的东西:

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

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

Then the .split() will split the string into an Array, and .pop() will give you the last item in the Array.

这篇关于如何在JavaScript中提取当前文档路径的URL的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆