Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.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 - Fatal编程技术网

使用javascript获取页面url

使用javascript获取页面url,javascript,Javascript,有人能推荐一种使用JavaScript从url获取页面名称的方法吗 例如,如果我有: http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3 我只需要获取“news.html”字符串 谢谢 var url = "http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3"; url = url.replace(/^.*\//, "").replace(/\?.*$/, "")

有人能推荐一种使用JavaScript从url获取页面名称的方法吗

例如,如果我有:

http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3
我只需要获取“news.html”字符串

谢谢

var url = "http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3";
url = url.replace(/^.*\//, "").replace(/\?.*$/, "");
你可以用
窗口替换
url
。位置

我想它是

window.location.pathname.replace(/^.*\/([^/]*)/, "$1");
所以


您可以通过
window.location.pathname
解析轻松完成此操作:

var file, n;

file = window.location.pathname;
n = file.lastIndexOf('/');
if (n >= 0) {
    file = file.substring(n + 1);
}
alert(file);

…或者正如其他人所说,您可以在一行中使用regexp来完成。一行看起来很密集,但上面有注释的行应该是一个不错的选择。

您可能还想在本地磁盘上查找文件路径, 您可能不希望在路径中包含任何哈希或get字符串-

String.prototype.fileName= function(){
 var f, s= this.split(/[#\?]/, 1)[0].replace(/\\/g,'/');
 s= s.substring(s.lastIndexOf('/')+ 1);
 f=  /^(([^\.]+)(\.\w+)?)/.exec(s) || [];
 return f[1] ||  '';
}

我认为你需要避开前面的斜杠美好的我从来不知道路径名!你不想在结尾加一个
$
?为了避免部分匹配?回答自己:不是在我的实验中,不是。我想*会吃掉路径名字符串的其余部分,我认为这是OP想要的。+1正则表达式的强大给我留下了深刻的印象,但我不能把它们作为注释来读。执行window.location.replace(/^.\/,“”)。replace(/\?。$/,“”);这会改变你的方向。
String.prototype.fileName= function(){
 var f, s= this.split(/[#\?]/, 1)[0].replace(/\\/g,'/');
 s= s.substring(s.lastIndexOf('/')+ 1);
 f=  /^(([^\.]+)(\.\w+)?)/.exec(s) || [];
 return f[1] ||  '';
}