chrisdillon
chrisdillon

Reputation: 556

How to extract part of location.href in JavaScript?

In this example, what's the regexp to to extract 'first' from location.href, such as:

http://www.mydomain.com/first/

Upvotes: 2

Views: 3608

Answers (5)

Tomalak
Tomalak

Reputation: 338336

Since you asked for a regex solution, this would be it:

^(?:[^:]+://)?[^/]+/([^/]+)

This matches all of these variants (match group one would contain "first" in any case):

  • http://www.mydomain.com/first/
  • http://www.mydomain.com/first
  • https://www.mydomain.com/first/
  • https://www.mydomain.com/first
  • www.mydomain.com/first/ (this one and the next would be for convenience)
  • www.mydomain.com/first

To make it "http://"-only, it gets simpler:

^http://[^/]+/([^/]+)

Upvotes: 4

annakata
annakata

Reputation: 75862

window.location.pathname

Upvotes: 5

Jesse Rusak
Jesse Rusak

Reputation: 57188

Perhaps not an answer to your question, but if you're writing in Javascript, you probably want to use location.pathname rather than extract it yourself from the entire href.

Upvotes: 11

serioys sam
serioys sam

Reputation: 2051

you can use window.location.host and window.location.search just check out this page for details

Upvotes: 1

Chris Doggett
Chris Doggett

Reputation: 20767

var re = /^http:\/\/(www.)?mydomain\.com\/([^\/]*)\//;
var url = "http://mydomain.com/first/";

if(re.test(url)) {
  var matches = url.match(re);
  return matches[2]; // 0 contains whole URL, 1 contains optional "www", 2 contains last group
}

Upvotes: 0

Related Questions