Anthony
Anthony

Reputation: 923

optional characters in javascript regular expression

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

Upvotes: 3

Views: 7524

Answers (2)

SLaks
SLaks

Reputation: 887433

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.

Upvotes: 5

Gumbo
Gumbo

Reputation: 655239

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 _.

Upvotes: 10

Related Questions