0

Why does this regex match, even though the IP address is missing its last number block?

var regex = '123\.(12[0-9]|13[0-5])\.[0-9]{1,3}\.[0-9]{1,3}';
var ipAddress = '123.123.123';
var r = new RegExp(regex).test(ipAddress); // =true
Manuel
  • 14,274
  • 6
  • 57
  • 130
  • 1
    When you build a regexp from a string (which, in this case, you don't have to do), you have to **double** the back-slash characters. – Pointy Jun 13 '19 at 00:17
  • 1
    [Generally, there's not much good reason to use new RegExp unless you need to dynamically create a regular expression from existing variables.](https://stackoverflow.com/questions/17863066/why-do-regex-constructors-need-to-be-double-escaped#answer-55793086). Use a regular expression literal instead – CertainPerformance Jun 13 '19 at 00:18
  • @CertainPerformance A duplicate answer does not make the question a duplicate. But that is a topic for meta I guess. – Manuel Jun 13 '19 at 00:23
  • It's basically the same thing. That is the canonical question for the problem you're having. The regular expression matches because regex constructors need to be double escaped, and the OP of the linked question is confused for the same reason, and the linked answers explain why, and what to do instead. – CertainPerformance Jun 13 '19 at 00:28

0 Answers0