开发者

Parse URL with Javascript [duplicate]

This question already has answers here: Closed 10 years ago.

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.

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?


You can use

var pagenum = location.pathname.match(/\/page\/(.*)/)[1];

It will extract anything past '/page/' in your URL;


Checkout this package jsuri

Or keep it simple http://james.padolsey.com/javascript/parsing-urls-with-the-dom/


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


Take a look at the documentation on the location object http://www.w3schools.com/jsref/obj_location.asp

You first want the "pathname" part, location.pathname

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜