In addition to escaping the backslash for the regex expression, you must also escape each backslash within the string literal. That is, the string literal
"\\"
evaluates to a one-character string sequence consisting of a single backslash. Since you need two backslashes to express a single backslash in your regular expression, you need four backslashes in your string literal to express two backslashes in your regular expression:
"\\\\"
This expresses a two-character sequence in the regular expression: one backslash, preceded by an escaping backslash, to fill out out regular expression. That is, these two expressions (using a regex literal and the RegExp
constructor) are equivalent:
/\\/
new RegExp("\\\\")
Each of these regular expression objects will match a single backslash.
Using a the RegExp
constructor, you can do: new RegExp("^[\\\\\\w., #&/-]+$")
; however, it seems like a regex literal would be cleaner and shorter with no disadvantages (as you don't dynamically build your regex using a varying string):
var regex = /^[\\\w., #&/-]+$/