使用JavaScript获取页面URL

8

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

例如,如果我有:

http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3

我只需要获取“news.html”字符串。

谢谢!

4个回答

15

你可以通过解析window.location.pathname相对轻松地实现这一点:

var file, n;

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

......或者像其他人所说的那样,你可以用一个正则表达式在一行中完成它。一行代码看起来有点复杂,但在上面添加注释应该是一个不错的选择。


2
+1 我对正则表达式的强大功能印象深刻,但我无法阅读它们。 - J.Hendrix

5

我认为这是

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

因此,
var pageTitle = window.location.pathname.replace(/^.*\/([^/]*)/, "$1");

我认为你需要在那里转义正斜杠。 :) - Vivin Paliath
不错!我从未听说过pathname - Vivin Paliath
你不想在末尾加上 $ 吗?以避免部分匹配? - T.J. Crowder
回答自己:在我的实验中没有。 - T.J. Crowder
我猜星号(*)将会消耗掉剩余的路径名字符串,这也是我认为原作者想要的结果。 - Pointy

3
var url = "http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3";
url = url.replace(/^.*\//, "").replace(/\?.*$/, "");

您可以将url替换为window.location

作为注意事项,执行 window.location.replace(/^.//, "").replace(/?.$/, ""); 将会重定向你。 - contactmatt

0

你可能需要在本地磁盘上查找文件路径,而且可能不希望在路径中包含任何哈希或获取字符串-

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] ||  '';
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接