espresso_coffee espresso_coffee - 4 years ago 380
Javascript Question

Regex Javascript?

I'm trying to write regular expression that allows alpha characters, space, dash, apostrophe and length 50. So far I have this:


I'm not sure where I should place the code for dash and apostrophe. If anyone can help pleases let me know. Thanks.

Answer Source

You need

/^[A-Za-z '-]{1,50}$/



When you use \s instead of a space, you will allow any whitespace.

The apostrophe can be placed anywhere inside the character class (so as not to ruin the ranges), and the hyphen at the start/end of the character class does not need to be escaped.

If you use {1,50} limiting quantifier, it means you allow 1 to 50 chars of the type specified in the character class. If you allow exactly 50 chars, use /^[A-Za-z\s'-]{50}$/. If you use just + instead, you will allow 1 or more characters.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download