Practical tools and techniques · Lesson 39 of 45
Searching with regular expressions
Text patterns, test, match and replace.
8 minutes2 games
A RegExp describes a text pattern. /cat/i searches case-insensitively. test returns a boolean; match retrieves matches. ^ anchors the start and $ the end; \d matches a digit and + repeats one or more times.
JavaScript
console.log(/^\d+$/.test("123"))
console.log(/cat/i.test("Cat nap"))
console.log("Order 12 and 7".match(/\d+/g))
console.log("a b".replace(/\s+/g, " "))| Tool | Use |
|---|---|
| Ignore case |
| Global matching |
| Match the whole string |
What's the output?
console.log(/^a+$/.test("aaa"))
console.log(/^a+$/.test("baaa"))What will this code print?
Exercise
Replace each whitespace run with one space and print it.
Expected output: Learn JS today
JavaScript
const text = "Learn JS today"
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.