Recipe 29 | Repeating Part of a Regex with Quantifiers |
Task
Suppose you want to add an option to your program that allows users to log in with a PIN code. The main benefit of using a PIN instead of a password is faster login. I tend to put my computer to sleep when I’m away, even for a short time. Conveniently, my OS lets me log in quickly with only a PIN code.
Say you want to implement a similar feature for your application. You need to write a regex pattern that 1) validates the input is digits and 2) ensures the number of digits is between 4 and 6 characters.
Solution
Place a pair of curly brackets after the \d character class to specify how many times the digits should occur:
| const re = /^\d{4,6} ... |
Get Text Processing with JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.