Exclude Literal backslash in Javascript Regular Expression
I'm writing a php forms class with client and server side validation. I'm having problems checking if a literal backslash ("\") exists in a string using regular expressions in javascript.
I 开发者_JAVA百科want to shy away from solutions other than using regex as this will reduce the amount of special cases between php and js AND reduce the amount of conditional code I need to write.
I've just been using this as an example of what a user may need in this forms class-
A password field that is a string between 6 and 12 chars long and that excludes "\","#","$","`"
I have tried:
^[^(\u0008#\$`)]{6,12}$
^[^(\b#\$`)]{6,12}$
^[^(\\#\$`)]{6,12}$
And none of them work for a backslash and I can't work out why. FYI: The latter works fine in PHP.
The regular expression \\
matches a single backslash. In JavaScript, this becomes re = /\\/
or re = new RegExp("\\\\")
.
ripped straight from http://www.regular-expressions.info/javascript.html
It looks like you've created a grouping of slash-hash-dollar-tick, rather than looking for any of those characters.
try this
var rgx = new RegExp(/^[^\\#\$`]{6,12}$/);
精彩评论