AI Hints
Home›JavaScript Tutorial›Sets, Maps and Regex
JavaScript · Lesson 110 of 138

Regular Expressions

Patterns in text.

⏱ 2 min read▶ Video at 2:12:19🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Regular Expressions
From the video: Regular Expressions
  • 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.

app.jsjavascript
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"));
Output
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.

keyvalue
\d \w \sdigit, 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, +, ^, $
Next up: Higher-Order Functions — functions as values