有人能推荐一种使用JavaScript从URL获取页面名称的方法吗?
例如,如果我有:
http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3
我只需要获取“news.html”字符串。
谢谢!
有人能推荐一种使用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);
......或者像其他人所说的那样,你可以用一个正则表达式在一行中完成它。一行代码看起来有点复杂,但在上面添加注释应该是一个不错的选择。
我认为这是
window.location.pathname.replace(/^.*\/([^/]*)/, "$1");
var pageTitle = window.location.pathname.replace(/^.*\/([^/]*)/, "$1");
pathname
! - Vivin Paliath$
吗?以避免部分匹配? - T.J. Crowdervar url = "http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3";
url = url.replace(/^.*\//, "").replace(/\?.*$/, "");
url
替换为window.location
。你可能需要在本地磁盘上查找文件路径,而且可能不希望在路径中包含任何哈希或获取字符串-
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] || '';
}