1

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

Ah geez I'm a noob. I should of checked there first! Thanks for your help.
Thanks to @Matthew Flaschen for catching something I didn't :| /facepalm
it's not you. It's a weird bug in StackOverflow's renderer.
something tells me it does escaping with a regex of its own ... but I caught that I needed to make the other two blocks ` escaped
1

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

1 Comment

Thanks for your help but it wasn't the grouping. It was that I was encapsulating in quotes so either had to lose the quotes or escape as "\\\\". Appreciate your help. (S.O. just isn't letting me choose an answer yet :S)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.