views:

42

answers:

2

I am trying to build a regular expression in javascript that checks for 3 word characters however 2 of them are are optional. So I have:

/^\w\w\w/i

what I am stumped on is how to make it that the user does not have to enter the last two letters but if they do they have to be letters

+7  A: 

You can use this regular expression:

/^\w{1,3}$/i

The quantifier {1,3} means to repeat the preceding expression (\w) at least 1 and at most 3 times. Additionally, $ marks the end of the string similar to ^ for the start of the string. Note that \w does not just contain the characters az and their uppercase counterparts (so you don’t need to use the i modifier to make the expression case insensitive) but also the digits 09 and the low line character _.

Gumbo
+2  A: 

Like this:

/^\w\w?\w?$/i

The ? marks the preceding expression as optional.

The $ is necessary to anchor the end of the regex.
Without the $, it would match a12, because it would only match the first character. The $ forces the regex to match the entire string.

SLaks