JavaScript Regular Expression Question Mark ?

***If this post helped you, please support this blog by clicking one of the links on this page. Thanks :) ***

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: $ ^

Leave a Reply