Chapter 17. Regular Expressions
Regular expressions provide sophisticated string matching functionality. If you want to match things that âlook likeâ an email address or a URL or a phone number, regular expressions are your friends. A natural complement to string matching is string replacement, and regular expressions support that as wellâfor example, if you want to match things that look like email addresses and replace them with a hyperlink for that email address.
Many introductions to regular expressions use esoteric examples such as âmatch aaaba and abaaba but not abba,â which has the advantage of breaking the complexity of regular expressions into neat chunks of functionality, but has the disadvantage of seeming very pointless (when do you ever need to match aaaba?). I am going to try to introduce the features of regular expressions using practical examples from the get-go.
Regular expressions are often abbreviated âregexâ or âregexpâ; in this book, weâll use the former for brevity.
Substring Matching and Replacing
The essential job of a regex is to match a substring within a string, and optionally replace it. Regexes allow you to do this with incredible power and flexibility, so before we dive into it, letâs briefly cover the non-regex search and replace functionality of String.prototype
, which is suitable for very modest search and replacement needs.
If all you need to do is determine if a specific substring exists in a bigger string, the following ...
Get Learning JavaScript, 3rd Edition 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.