December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 48 | Testing a Pattern with the Negative Lookahead |
Suppose you want to match any two-digit number except 41, 66, and 77 because these are retired jersey numbers, so you want to make sure they don’t get reassigned to a new player.
You could use several character classes matching a range between 00 to 40, 42 to 65, 67 to 76, and 78 to 99. But you’d end up with a very long and complicated pattern. Fortunately, there’s a more compact way to get the same result with lookahead assertions.
Use a negative lookahead assertion denoted by (?! ... ):
| | const re = /#(?!41|66|77)\d{2}/ |
| | |
| | re.test("#00"); // → true |
| | re.test("#39"); // → true |
| | re.test("#41"); // → false ... |
Read now
Unlock full access