Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.3 — Regular Expressions Basics
JavaScript · Example 1 of 3

test, match and the flags

\D (not a digit) with g strips every space and dash in one go. match without g returns the first match (the console shows its items; it also has .index and .groups). exec is the regex-side version of match without g.

A regular expression (regex) is a small pattern language for describing text, like "three digits, a dash, then four digits". You write it as /pattern/flags and use it with test, match, matchAll, replace and split to check, find, extract and rewrite text.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write isStrongPassword(p) that returns true when p has at least 8 characters, at least one digit, one lower-case and one upper-case letter. Use several small regexes rather than one giant one.

02

Write extractHashtags(text) that returns an array of hashtag words without the #, so extractHashtags("Learning #js and #CSS!") returns [ 'js', 'CSS' ].

03

Write camelToKebab(name) that turns "backgroundColor" into "background-color".

Explain it without notes

01

What is the difference between test, match and matchAll?

02

What does the g flag change, and why can it make test give different answers?

03

What are greedy and lazy quantifiers? Give an example.

04

How do you safely build a regex from user input?

test, match and the flags

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

9876543210 true
[ 'cats', 'Cats' ]
null
[ '1', '22', '333' ]
[ '1' ]
<b>hi</b> <b>
true false
[ 'one', 'two', 'three' ]
false true