59

What does the ?! mean in the following regex expression?

new RegExp('http:\/\/(?!' + location.hostname + ')')
Francesco Boi
  • 7,133
  • 10
  • 64
  • 105
Ricky
  • 32,609
  • 37
  • 88
  • 131

3 Answers3

86

It's a negative lookahead, which means that for the expression to match, the part within (?!...) must not match. In this case the regex matches http:// only when it is not followed by the current host name (roughly, see Thilo's comment).

kumarharsh
  • 18,026
  • 7
  • 71
  • 97
Joey
  • 330,812
  • 81
  • 665
  • 668
  • +1 or, because of lack of proper escaping, only if it is not followed by something similar to the host name, with dots replaced by stuff admissible. – Thilo Aug 31 '12 at 07:36
  • 1
    Indeed. It probably won't make *that* much of a difference in most cases, though. Although, in the light of the recent Stripe CTF, such a lapse could be both hard to spot and may allow things that were not intended ;-) – Joey Aug 31 '12 at 07:38
  • 1
    Yes, won't matter. It's just that years of fixing injection vulnerabilities make these things stand out for me now ... – Thilo Aug 31 '12 at 07:39
  • 1
    This answer has been added to the [Stack Overflow Regular Expression FAQ](http://stackoverflow.com/a/22944075/2736496), under "Lookarounds". – aliteralmind Apr 10 '14 at 00:29
5

It's a negative lookahead, you can check here for more information.

npinti
  • 51,070
  • 5
  • 71
  • 94
0

It's a look around.

location.hostname must not follow http:\/\/

Jürgen Steinblock
  • 29,009
  • 23
  • 111
  • 177