Regular Expressions
Patterns in text.
How do you check whether some text looks like an email, or pull every number out of a sentence? Regular expressions, or regex, describe patterns in text. They look cryptic at first, but a few pieces go a long way.

- Does it look like an email?
- Find every number
- Patterns in text
Test, match, replace
A regex goes between slashes. Backslash d means a digit, and plus means one or more. Test checks for a match. Match with the g flag, for global, finds every match. And replace swaps matches for new text. The last pattern checks for a simple email shape. Run it.
const text = "Order 42 shipped 3 items for $19";
console.log(/\d+/.test(text));
console.log(text.match(/\d+/g));
console.log(text.replace(/\d+/g, "#"));
const email = /^[\w.]+@[\w]+\.[a-z]{2,}$/;
console.log(email.test("ana@mail.com"), email.test("not an email"));true [ '42', '3', '19' ] Order # shipped # items for $# true false
Common pieces
Backslash d is a digit, backslash w is a letter, digit, or underscore, and backslash s is a space. A dot means any character. Plus means one or more, and star means zero or more. The caret means the start, and dollar means the end. Square brackets mean any one of these characters.
| key | value |
|---|---|
| \d \w \s | digit, word char, space |
| + * ? | 1+, 0+, optional |
| ^ $ | start, end |
| [abc] | one of these |
Summary
Regular expressions describe patterns. Test checks for a match, match finds them, and replace swaps them. Next, functions that work with other functions.
Key takeaways- /pattern/flags
- test, match, replace
- \d, \w, +, ^, $