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.
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.
Write extractHashtags(text) that returns an array of hashtag words without the #, so extractHashtags("Learning #js and #CSS!") returns [ 'js', 'CSS' ].
Write camelToKebab(name) that turns "backgroundColor" into "background-color".
Explain it without notes
What is the difference between test, match and matchAll?
What does the g flag change, and why can it make test give different answers?
What are greedy and lazy quantifiers? Give an example.
How do you safely build a regex from user input?
Preview
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