REGEX: Trying to create a reg. exp. that can find a string in the referrers host name
I am trying to create a JavaScript regular expression that can find a keyword in the referrers host nam开发者_运维知识库e. It cannot be in the file path, just the host name. So... these should pass:
http://keyword.com/
http://www.keyword.com/
http://keyword.example.com/
http://examplekeyword.com/
But these should not:
http://example.com/keyword
http://example.com/?q=keyword
http://example.com/example/keyword.php
I also unsure how to create the regex. I've seen var re = new regex('actual regex'); and also mystring.search('actual regex'); . Any help would be greatly appreciated!
^http://[^/]*keyword
Will match if the keyword is present. What it returns is kinda odd (http://keyword
for http://keyword.com
), but it's the least complex you can do.
If you're interested in the full hostname being returned,
^http://[^/]*keyword[^/]*
Returns http://thekeywordexists.com
for http://thekeywordexists.com/foo
.
There are a number of ways to use regular expressions in Javascript. Regular-Expressions.info's Javascript page is likely a good resource for this. (Performance tip: create the RegExp object once and make it a variable, rather than creating it every time you use it :o)
I believe that this does what you want:
/^http:\/\/[^\/]*keyword\./.test('http://www.keyword.com')
A little explanation:
- start with
http
followed by://
(^http:\/\/
) - follwed by everything besides
/
- followed by
keyword
followed by a.
精彩评论