Sikau

Advanced JavaScript · Day 15 · about 30 min

Regular expressions

Patterns for finding text.

Search by shape

"Find every phone number" or "is this a valid postcode?" — you're describing the shape of text, not exact words. A regular expression (regex) is a tiny language for shapes of text.

The building blocks

const text = "Call 98-41234567 or 98-45550000 before 6pm";

console.log(/\d+/.test(text));
console.log(text.match(/\d{2}-\d{8}/));
console.log(text.match(/\d{2}-\d{8}/g));
console.log(/^call/i.test(text));
  • \d digit, \w letter/digit/_, \s space, . any character
  • [aeiou] any one of these, [^0-9] anything but these
  • + one or more, * zero or more, ? optional, {2,4} between 2 and 4
  • ^ start, $ end, \b word boundary
  • Flags: g all matches, i ignore case

The rest of this lesson

  • Reading a regex left to rightexplain
  • Escaping and testing patternsexplain
  • Predict the outputpredict
  • Read the patternmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript