Reputation: 556
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
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
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
Reputation: 2051
you can use window.location.host and window.location.search just check out this page for details
Upvotes: 1
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