有人可以推荐一种方法从使用JavaScript的URL获取页面名称吗?使用javascript获取页面url
举例来说,如果我有:
http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3
我只需要得到 “news.html” 串
谢谢!
有人可以推荐一种方法从使用JavaScript的URL获取页面名称吗?使用javascript获取页面url
举例来说,如果我有:
http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3
我只需要得到 “news.html” 串
谢谢!
您可以通过window.location.pathname
解析做到这一点很容易地:
var file, n;
file = window.location.pathname;
n = file.lastIndexOf('/');
if (n >= 0) {
file = file.substring(n + 1);
}
alert(file);
......或者像其他人所说的那样,你可以在一行中使用正则表达式。一条有点密集的线条,但有一条评论,它应该是一个很好的途径。
+1我对正则表达式的力量印象深刻,但我无法读懂它们。 –
var url = "http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3";
url = url.replace(/^.*\//, "").replace(/\?.*$/, "");
您可以window.location
作为一个说明得到的字符串,这样做window.location.replace(/^.*\//,“”).replace(/\?.*$/,“”);会重定向你。 – contactmatt
替代url
我认为这是
window.location.pathname.replace(/^.*\/([^/]*)/, "$1");
所以,
var pageTitle = window.location.pathname.replace(/^.*\/([^/]*)/, "$1");
你可能也想找到文件路径在本地磁盘上, ,你可能不希望包括任何哈希值或路径 -
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] || '';
}
我喜欢TJ的解决方案 – Alex