December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 24 | Asserting the Start or End of a String with ^ and $ |
Suppose you have an input field in your app that allows customers to enter their order number and track their package. You want to ensure the user input is a number before searching it in your database. If you are a bit familiar with regex, you know that to match a digit with regex, you can use \d. And to match one or more digits, you can put a plus sign right after it like this:
| | const input = "8751409"; |
| | |
| | function verifyDigits(input) { |
| | const re = /\d+/; |
| | return re.test(input); |
| | } |
| | |
| | verifyDigits(input); // → true |
This regex matches “8751409” as you intended. But it also matches a string like “123abc” or “abc123abc”:
Read now
Unlock full access