espresso_coffee espresso_coffee - 1 month ago 19
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:

/^([A-Za-z\s].{1,50})$/


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

Answer

You need

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

or

/^[A-Za-z\s'-]{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.

Comments