Javascript 使用javascript获取页面url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2426958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get page url using javascript
提问by Alex
Could someone recommend a way to get page name from a url using JavaScript?
有人可以推荐一种使用 JavaScript 从 url 获取页面名称的方法吗?
For instance if I have:
例如,如果我有:
http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3
I just need to get "news.html" string
我只需要获取“news.html”字符串
Thanks!
谢谢!
回答by T.J. Crowder
You can do this pretty easily via window.location.pathnameparsing:
您可以通过window.location.pathname解析很容易地做到这一点:
var file, n;
file = window.location.pathname;
n = file.lastIndexOf('/');
if (n >= 0) {
file = file.substring(n + 1);
}
alert(file);
...or as others have said, you can do it with a regexp in one line. One kinda dense-looking line, but with a comment above it, should be a good way to go.
...或者正如其他人所说,您可以在一行中使用正则表达式。一条看起来有点密集的线,但上面有一条评论,应该是一个不错的选择。
回答by Pointy
I think it's
我想这是
window.location.pathname.replace(/^.*\/([^/]*)/, "");
So,
所以,
var pageTitle = window.location.pathname.replace(/^.*\/([^/]*)/, "");
回答by Vivin Paliath
var url = "http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3";
url = url.replace(/^.*\//, "").replace(/\?.*$/, "");
You can substitute urlwith window.location
你可以url用window.location
回答by kennebec
You might want to also find file paths on a local disk, and you might not want to include any hash or get strings in the path-
您可能还想在本地磁盘上查找文件路径,并且您可能不想在路径中包含任何散列或获取字符串 -
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] || '';
}

