December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 26 | Matching One of Several Alternatives with the Vertical Bar (|) |
Imagine you want to match specific variations of the word “week,” including “weekend” and “weekly,” but not “weekday.” You want the match to be at word boundaries, so other words like “Newsweek” wouldn’t count as a match. What you need is a way to define alternative patterns in the regex.
Use a vertical bar (|) to form an alternation. The vertical bar character will tell the regex engine to match any one of a series of patterns:
| | const re = /\bweek\b|\bweekend\b|\bweekly\b/; |
| | |
| | re.test("How much do you earn per week?"); // → true |
| | re.test("Employees are paid weekly."); // → true |
| | re.test( ... |
Read now
Unlock full access