Command Palette

Search for a command to run...

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

The lastIndex trap with g and test

A regex with g (or y) remembers where the last match ended in lastIndex and starts the next search there. For yes-or-no checks, leave out 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?

The lastIndex trap with g and test

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

true 2
false 0
true 2
true true true
true false true