简体   繁体   中英

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 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}$/);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM