views:

32

answers:

2

I am trying to create a JavaScript regular expression that can find a keyword in the referrers host name. 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!

A: 

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 .
WoLpH
Doesn't match `http://examplekeyword.com/`, as required :/
Matchu
Yes, I overlooked that example. In that case it's even simpler.
WoLpH
+2  A: 
^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)

Matchu
That also matches `http://somekeyword.com/`, although I don't know if that is acceptable.
WoLpH
@WoLpH - I'm not sure I understand. `http://examplekeyword.com/` is equivalent, and lists as a test that should pass.
Matchu
Additionally, the assumption is that we should match keywordexample too.... which the above does.
Peter Ajtai
Indeed, I overlooked that example. In that case it's correct :)
WoLpH