Kei*_*umi 13 javascript regex jquery
我正在尝试在没有任何参数的情况下在Javascript中提取当前文件名.
$(location).attr('href').match(/([a-zA-Z\-\_0-9]+\.\w+)$/);
var current_path = RegExp.$1;
if ((current_path == 'index.html') || ...) {
// something here
}
Run Code Online (Sandbox Code Playgroud)
但是当您访问http://example.com/index.html?lang=ja时,它根本不起作用.当然,文件名将随机更改.
任何的想法?
use*_*716 44
如果您要查找路径中的最后一项,请尝试以下操作:
var current_path = window.location.pathname.split('/').pop();
Run Code Online (Sandbox Code Playgroud)
这个:
window.location.pathname
Run Code Online (Sandbox Code Playgroud)
会给你这样的东西:
"/questions/6543242/how-to-extract-the-filename-of-url-in-javascript"
Run Code Online (Sandbox Code Playgroud)
然后.split()将字符串拆分为一个数组,.pop()并将为您提供数组中的最后一项.
ken*_*bec 10
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'
Run Code Online (Sandbox Code Playgroud)
URL的文件名是最后"/"一个到达以下之一的所有内容:1.)a "?"(URL查询的开头),或2.)a "#"(URL片段的开头),或3.)字符串的结尾(如果没有查询或片段).
这个测试正则表达式的功效:
.match(/[^\/?#]+(?=$|[?#])/);
| 归档时间: |
|
| 查看次数: |
30014 次 |
| 最近记录: |