Archive for April 15, 2007

JavaScript Regular Expression Question Mark ?

Posted in JavaScript, Software, Web, programming on April 15, 2007 by Joey

The Question Mark (?) special character is used in JavaScript regular expressions to match zero or one occurrences of the previous item.

document.write(/^\d{2}\d?$/.test(123));

The preceding code will return true for exactly two digits, with an optional third digit. If the test number is updated to 1234, the code will return false.

Related articles:
JavaScript Regular Expressions
JavaScript Regular Expression Special Characters: $ ^