2010-03-11 51 views
8

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

举例来说,如果我有:

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

我只需要得到 “news.html” 串

谢谢!

+1

我喜欢TJ的解决方案 – Alex

回答

14

您可以通过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我对正则表达式的力量印象深刻,但我无法读懂它们。 –

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

您可以window.location

+0

作为一个说明得到的字符串,这样做window.location.replace(/^.*\//,“”).replace(/\?.*$/,“”);会重定向你。 – contactmatt

5

替代url我认为这是

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

所以,

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

我认为你需要在那里逃避正斜线。 :) –

+0

是的,我明白了 - 谢谢! – Pointy

+0

不错!我从来不知道'路径名'! –

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