JavaScript lesson · 18 min

JavaScript Regular Expressions

Find and validate text patterns with regular expressions and clear match output.

Code runs locally in your browser

What you will practice

  • Create a regular expression.
  • Find matches in a string.
  • Use test for simple validation.

What this means

A regular expression, often shortened to regex, is a pattern for matching text.

Regex is useful when plain string methods are too limited. You can search for emails, IDs, dates, repeated spaces, file extensions, or words with a certain shape.

Regex can become hard to read quickly. Small patterns with clear names are usually better than one giant clever pattern.

If this is your first time seeing this

Regex is a pattern language for text. It helps you find text that has a shape, not just exact words.

Use regex carefully: it is powerful, but unreadable patterns become bugs waiting to happen.

Mini glossary

Pattern
The rule a regular expression uses to match text.
Flag
A modifier such as `g` that changes how the regex searches.
test
A regex method that returns true or false.

Example from everyday life

A regular expression is like a metal detector for text. You do not know exactly where the target is, but you describe the shape of what you are looking for and scan the whole area.

How it works step by step

  1. The code stores text that contains two email addresses.
  2. The regex looks for a simple email-shaped pattern.
  3. `match` returns all matches because the regex uses the `g` flag.
  4. `test` checks whether a separate value looks like an email.

Where you will use this

  • A signup form checks whether an email field has an email-like shape.
  • A log tool extracts request IDs or error codes from pasted logs.
  • A text cleanup tool finds repeated whitespace or unwanted characters.

Before you run the code

Regex validation is not the same as perfect truth. A simple email regex can catch obvious mistakes, but real email rules are more complicated.

Use regex as a practical text tool, and keep important business validation on the server too.

Common beginner mistakes

  • Writing a pattern that is too broad and matches unwanted text.
  • Writing a pattern that is too strict and rejects valid input.
  • Forgetting the `g` flag when you want all matches, not only the first one.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingFinds email-like matches
WaitingValidates a candidate string

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Add another email address to the text.
  • Remove the `g` flag and see how the result changes.
  • Change the candidate to invalid text and check the boolean output.