有人可以推荐一种使用JavaScript从网址获取网页名称的方法吗?
例如,如果我有:
http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3
Run Code Online (Sandbox Code Playgroud)
我只需要获取"news.html"字符串
谢谢!
T.J*_*der 14
你可以通过window.location.pathname解析很容易地做到这一点:
var file, n;
file = window.location.pathname;
n = file.lastIndexOf('/');
if (n >= 0) {
file = file.substring(n + 1);
}
alert(file);
Run Code Online (Sandbox Code Playgroud)
......或者正如其他人所说,你可以用一行正则表达式来完成它.一个看起来很密集的线条,但上面有一个评论,应该是一个很好的方式.
我想这是
window.location.pathname.replace(/^.*\/([^/]*)/, "$1");
Run Code Online (Sandbox Code Playgroud)
所以,
var pageTitle = window.location.pathname.replace(/^.*\/([^/]*)/, "$1");
Run Code Online (Sandbox Code Playgroud)