0

For my regex:

^(http(s)?\://)?(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$

I am wondering as to why "john" passes? This regex is only supposed to pass for URLs

> var j = new RegExp("^(http(s)?\://)?(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$");
> j.test("john")
> true

There is a required \. within the regex line

Liondancer
  • 15,721
  • 51
  • 149
  • 255

1 Answers1

7

You are constructing your regular expression by passing a string to the RegExp constructor function.

While \ has special meaning as an escape character in regular expressions, it also has a similar meaning in string literals.

The \\ in the string literal has been parsed into \ in the string and thus is treated as an escape character in the regular expression.

You need to provide an escaped \ and and escaped escape character.

So for a regular expression that matches a single \ you need:

var myRegEx = new RegExp("\\\\")

I suggest avoiding the constructor function and using a regex literal instead.

var myRegEx = /\\/;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335