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
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
Share Improve this question asked May 4, 2010 at 21:19 AnthonyAnthony 9233 gold badges23 silver badges35 bronze badges 2-
Does
/^\w\w?\w?$/i
work for you? – tloflin Commented May 4, 2010 at 21:22 - I did have to change it to \d and \Dbecause cause of the data i was testing but the answers were still correct about the optional characters – Anthony Commented May 6, 2010 at 22:58
2 Answers
Reset to default 10You 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 a
–z
and their uppercase counterparts (so you don’t need to use the i modifier to make the expression case insensitive) but also the digits 0
–9
and the low line character _
.
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.