Recipe 27 | Matching One of Several Characters with the Character Class |
Task
Suppose you want to find a word in a document even if it is misspelled. For example, the word “license” is one of the most misspelled words in English. You want to write a pattern that matches “license,” “licence,” “lisence,” or “lisense” in a document.
Solution
Use a character class:
| const re = /li[sc]en[sc]e/; |
| |
| re.test("A driver's license"); // → true |
| re.test("A driver's lisense"); // → true |
| re.test("A driver's licence"); // → true |
| re.test("A shopping list"); // → false |
A character class matches only one out of the specified characters. In this code, the specified characters are “s” ...
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.