使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:03:53  来源:igfitidea点击:

Parse URL with Javascript

javascripturl

提问by Tommy

Possible Duplicate:
How do I parse a URL into hostname and path in javascript?

可能重复:
如何将 URL 解析为 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

回答by rodneyrehm

URI.jsis a library for working with URLs. It can not only parse URLs, but also offers a simple fluent API (jQuery like) for modifying URLs.

URI.js是一个用于处理 URL 的库。它不仅可以解析 URL,还提供了一个简单的 fluent API(类似 jQuery)来修改 URL。

回答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