Literal syntax
/pattern/ creates a RegExp directly.
RegExp objects describe text patterns. They are useful for validation, searching, extraction and controlled replacement.
const pattern = /javascript/i;
console.log(pattern.test("JavaScript basics"));
Regular Expressions
A regular expression describes a text pattern. JavaScript can use that pattern to test text, find matches, extract parts or replace text.
Regex syntax is powerful, but it can become unreadable quickly. Good regex code names the pattern, limits scope and explains non-obvious intent.
Use regex for pattern matching, not for parsing every possible structured language. HTML, JSON and URLs usually deserve proper parsers or dedicated APIs.
/pattern/ creates a RegExp directly.
new RegExp(value) builds a pattern dynamically.
Returns true or false for a match.
A small regex is usually better than one huge pattern.
Examples
const slugPattern = /^[a-z0-9-]+$/;
function isSlug(value) {
return slugPattern.test(value);
}
if (/^[a-z0-9-]+$/.test(value)) {
save(value);
}
// Works, but the intent is hidden.
Code patterns
These examples are intentionally small. Regex becomes useful when each pattern has one clear job and a readable method around it.
Use a literal for static patterns.
const pattern = /javascript/i;
pattern.test("JavaScript basics");
Use the constructor for dynamic pattern text.
const word = "css"; const pattern = new RegExp(word, "i");
Use anchors to match the whole string.
const slugPattern = /^[a-z0-9-]+$/;
console.log(slugPattern.test("array-methods"));
match returns details when a match exists.
const text = "Version 2026";
const match = text.match(/\d{4}/);
console.log(match?.[0]);
Rules that matter
Regular expressions are compact by design. Good JavaScript around the pattern is what makes them safe to maintain.
A variable name explains what the regex means.
^ and $ prevent partial matches.
User-provided pattern text can change regex meaning.
Large regexes are hard to review.
Do not parse JSON or HTML with one regex.
Regex behavior changes quickly with small syntax changes.
Production thinking
Regex can remove a lot of manual string code, but unreadable regex can also become a hidden bug factory.
Validation patterns should produce helpful messages, not just reject input silently.
Production regexes should be named, tested and limited to the problem they actually solve.
Regex is useful for slug validation and URL cleanup, but canonical URL rules should be explicit.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
Regex skill is not memorizing every token. It is knowing how to build small patterns and choose the right string method around them.