如何在JavaScript中提取当前文档路径的URL的文件名
How to extract the filename of the URL of the current document path in JavaScript?
我试图在没有任何参数的情况下提取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"
相关文章:
- 使用promise和mongoose对文档进行排序
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- Ajax请求文档就绪会导致jquery加载缓慢
- MongoDB (php) - 以数组而不是多个属性的形式返回文档属性
- 谷歌文档表面引擎
- 来自文档或下一个静态父级的事件委派
- 如何将childNodes用于XML文档
- 文档就绪提供了错误的选择器高度
- 将当前用户的 ID 推送到 meteorjs 中集合/文档的内部数组
- 未捕获的语法错误:无法在“文档”上执行“查询选择器”
- BrowserId登录请求在文档加载时被调用
- 从Javascript和Php变量创建Html模板文档
- 如何通过谷歌应用程序脚本从谷歌文档中的位置确定命名范围
- 在jquery文档准备好之前加载Modernizr
- 如何判断何时将dom节点添加到文档中
- 使用加载的文档's路径作为相对路径的根,而不是源文档's路径来加载HTML
- 如何使用word JavaScript API在给定路径中保存word文档
- 文档的相对路径,从href传递到Javascript函数,去掉反斜杠和句号
- 在mongoose中关闭从嵌入文档自动创建索引路径
- 谷歌应用程序为创建的文档指定路径