使用 Javascript 解析 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4140324/
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
Parse URL with Javascript
提问by Tommy
Possible Duplicate:
How do I parse a URL into hostname and path in javascript?
I'm trying to parse the url of the page. For example the current page is location.href.
我正在尝试解析页面的 url。例如当前页面是location.href。
So the main page of my blog, if I use alert(location.href); it will return “http://diaryofthedead.co.cc/” in an alert box. If I use alert(location.href); on page two of my blog, it will return “http://diaryofthedead.co.cc/page/2” in an alert box. Is there any way to parse the URL to get the number at the end. Does anyone know how I could do that? Could I use wildcard or something, to do something like: location.href+”page/”+*; While * is equal to whatever follows “page/”, and then turn * into a variable?
所以我博客的主页,如果我使用 alert(location.href); 它将在警告框中返回“ http://diaryofthedead.co.cc/”。如果我使用 alert(location.href); 在我博客的第二页,它会在警告框中返回“ http://diaryofthedead.co.cc/page/2”。有什么方法可以解析URL以获取最后的数字。有谁知道我怎么能做到这一点?我可以使用通配符或其他东西来做类似的事情:location.href+”page/”+*; 而 * 等于“page/”后面的任何内容,然后将 * 变成一个变量?
采纳答案by MartinodF
You can use
您可以使用
var pagenum = location.pathname.match(/\/page\/(.*)/)[1];
It will extract anything past '/page/' in your URL;
它将提取 URL 中“/page/”之后的任何内容;
回答by doublejosh
Checkout this package jsuri
签出这个包jsuri
Or keep it simple http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
或者保持简单http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
回答by rodneyrehm
回答by Geuis
Take a look at the documentation on the location object http://www.w3schools.com/jsref/obj_location.asp
查看有关位置对象的文档http://www.w3schools.com/jsref/obj_location.asp
You first want the "pathname" part, location.pathname
您首先需要“路径名”部分,location.pathname