28

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?

Community
  • 1
  • 1
Tommy
  • 365
  • 1
  • 5
  • 7
  • 2
    @jnpcl I actually came across that before asking this. It was a bit useful, but still didn't provide the answer I was looking for. If I used the answer to that question, I would get "page/2" instead of "2". – Tommy Nov 10 '10 at 01:10

4 Answers4

28

You can use

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

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

MartinodF
  • 8,157
  • 2
  • 32
  • 28
14

Checkout this package jsuri

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

doublejosh
  • 5,548
  • 4
  • 39
  • 45
10

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.

rodneyrehm
  • 13,442
  • 1
  • 40
  • 56
9

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

Geuis
  • 41,122
  • 56
  • 157
  • 219
  • 24
    That's a stupid reason to downvote. W3Schools isn't perfect and is often wrong, but if the poster checked the site and the contents of the one particular page he linked to are fine, what's the problem? @Felix – Mahmoud Al-Qudsi May 06 '12 at 09:50
  • True. Everybody does stupid stuff sometimes. That page has exactly one mistake, and it's minor, and an omission, but it's minor as well, so I'd undo that. – Félix Saparelli May 06 '12 at 11:34