12 Wrangling regular expressions
This chapter covers
- A refresher on regular expressions
- Compiling regular expressions
- Capturing with regular expressions
- Working with frequently encountered idioms
Regular expressions are a necessity of modern JavaScript development. Frequently, a half-screen of complex parsing logic can be distilled down to a single regular expression pattern. Regular expressions trivialize the process of tearing apart strings and looking for information.
At the same time, it’s important to understand the limitations of regular expressions. Not all string patterns can be expressed as a (reasonably sized) regular expression. Developers are always tempted to use a regular expression whenever they need to parse a string, whereas a JavaScript Ninja knows when to use a regular expression and when to use a full-fledged parser.
We’ll start with the basics of regular expressions, then touch on advanced features added by the latest ECMAScript specs. Along the way, we’ll look at some alternatives for those complex parsing patterns that regular expressions can’t handle.
12.1 Why regular expressions rock
Let’s say we want to validate that a string, perhaps entered into a form by a website user, follows the format for a nine-digit U.S. postal code. Specifically, the U.S. Postal Service insists that a postal code (also known as a ZIP code) follows this specific format:
ddddd-dddd