Reputation: 5780
Say, I'd like the condition to be true if the document.location equals http://www.example.com
or http://www.example.com/example/anythinghere/
, but FALSE if the location does not fit exactly, for example http://www.example.com/example/anythinghere/sdjfdfasdfaf
will return FALSE.
Naturally, I'd write something like:
if(document.location == "http://www.example.com/" ||
document.location == "http://www.example.com/example/*/")
However, I know the good ol' asterisk wildcard won't work, and, as an amateur with regex, I can't manage to find the proper setup to look for an exact match to the pattern. What would you suggest for the second half of the conditional?
Upvotes: 0
Views: 1950
Reputation: 19423
Try the following:
if(document.location == "http://www.example.com/" ||
/^http:\/\/www.example.com\/example\/[^\/]+\/?$/.test(document.location))
The will test if your URL matches http://www.example.com/
exactly, or if it uses a regular expression to see if it matches http://www.example.com/example/ANYTHING_HERE_EXCEPT_FORWARD-SLASH/
.
Upvotes: 1
Reputation: 13266
Try matching using:
regex = /^http:\/\/www.example.com\/(?:example\/(?:[^\/]+\/)?)?$/
Specifically this says:
If you then apply this I think it covers all your cases:
regex.exec("http://www.example.com/example/anythinghere/") // matches
regex.exec("http://www.example.com/example/anythinghere") // doesn't match (no trailing slash)
regex.exec("http://www.example.com/example/anythinghere/qwe") // doesn't match (extra end chars)
regex.exec("http://www.example.com/exam") // doesn't match (no subdir)
regex.exec("http://www.example.com/") // matches
Upvotes: 1
Reputation: 38345
The following regular expression should do it:
/^http:\/\/www\.example\.com\/(?:example\/[^\/]+\/)?$/
That's the starting part of http://www.example.com/
, followed by an optional /example/somecharacters/
.
Usage:
var re = /^http:\/\/www\.example\.com\/(?:example\/[^\/]+\/)?$/;
if(re.test(document.location.href) {
}
Upvotes: 1
Reputation: 785866
You can use lookahead based regex:
m = location.href.matches(/www\.example\.com\/(?=example\/)/i);
Upvotes: 0
Reputation: 1170
try a regex that only acepts letters, like [a-zA-Z]+
, otherwise http://www.example.com/example/;:ª*P=)#/")#/
will be valid
http://www.example.com/example/qwerty/uiop/
will be valid too? ends with /
but have two middle levels.
Upvotes: 0