espresso_coffee espresso_coffee - 4 months ago 31
Javascript Question

Allows alpha characters, space, dash, apostrophe and length <= 50 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.


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.