In this example, what's the regexp to to extract 'first' from location.href, such as:
+4
A:
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://[^/]+/([^/]+)
Tomalak
2009-03-09 16:34:16
really? a regex when it's available as a property?
annakata
2009-03-09 16:44:23
@annakata: well, that is what cdillon asked for. But yeah, kinda backwards.
Shog9
2009-03-09 16:47:25
@annakata: location.pathname would require some post-processing as well, since the OP seems to ask for the "first" part only. Admittedly, this could be done with split("/")[0], but a) I don't see the real drawback of regex here, and b) he may also want to match the rest of the URL for some reason.
Tomalak
2009-03-09 16:49:13
That gives me:http://www.mydomain.com/first,http://,first
cdillon
2009-03-09 16:51:53
Yeah, you are right. I changed the regex a bit (made the first group a non-capturing one), so now it should give you this: ["http://www.mydomain.com/first", "first"]. Array position 0 always is the whole match, array position 1 is match group 1.
Tomalak
2009-03-09 16:57:59
I went with the location.pathname, but thanks for the regex answer, I will study it.
cdillon
2009-03-09 17:00:14
@tomalak: just clarity and a probably insignificant performance hit. The extension of the regex is certainly valuable (and as you point out, the OP probably needs to do *some* string manip on the property, but I think it's likely that it's only simple stuff and the property will be clearer in intent
annakata
2009-03-09 17:02:15
I think the "location.pathname" solution is the one that better suits your problem.
Tomalak
2009-03-09 17:02:18
@annakata: Yeah, probably it's also better because avoiding regex for trivial things makes code more maintainable -- especially when you admit to be a "RegExp noob", as the OP did originally. Ah, well. :-)
Tomalak
2009-03-09 17:05:32
A:
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
}
Chris Doggett
2009-03-09 16:35:07
+1
A:
you can use window.location.host and window.location.search just check out this page for details
serioys sam
2009-03-09 16:35:11
+8
A:
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.
Jesse Rusak
2009-03-09 16:35:43