- Courses
- đ»Programming Languages
- đJavaScript
- Tooling and Performance
- Regular Expressions (Regex)
On this page
Regular Expressions (Regex)
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
A Regular Expression, or Regex, is a sequence of characters that forms a search pattern. In JavaScript, Regex is an essential tool for high-performance string searching, data validation, and complex text transformations. While often considered intimidating due to its dense syntax, Regex follows a strict logical structure that, once mastered, allows an engineer to perform in a single line of code what might otherwise take dozens of lines of standard logic.
Fundamentals and Syntaxâ
In JavaScript, a Regular Expression is an object. You can create one using the literal syntax (enclosed in forward slashes) or the RegExp constructor.
const literalRegex = /pattern/flags;
const constructorRegex = new RegExp('pattern', 'flags');
Character Classes and Meta-charactersâ
These are the building blocks that allow you to match types of characters rather than specific literals.
.: Matches any single character except newline.\d: Matches any digit (0-9).\w: Matches any alphanumeric character (including underscores).\s: Matches any whitespace (spaces, tabs, line breaks).[abc]: A character set; matches any one of the characters 'a', 'b', or 'c'.[^abc]: A negated set; matches anything except 'a', 'b', or 'c'.
Quantifiers: Controlling Frequencyâ
Quantifiers specify how many times the preceding character or group should occur in the string.
*: Matches 0 or more times.+: Matches 1 or more times.?: Matches 0 or 1 time (optional).{n}: Matches exactly $n$ times.{n,m}: Matches between $n$ and $m$ times.
Greedy vs. Lazy Matchingâ
By default, quantifiers are greedy, meaning they match as much of the string as possible. Adding a ? after a quantifier (e.g., +?) makes it lazy, forcing it to match the smallest possible segment.
Anchors and Boundariesâ
Anchors do not match characters; they match positions within the string. This is vital for ensuring a pattern matches an entire string rather than just a segment of it.
^: Matches the beginning of the string.$: Matches the end of the string.\b: Matches a word boundary (the position between a word character and a non-word character).
Advanced Assertions: Lookaheads and Lookbehindsâ
Expert-level Regex often requires matching a pattern only if it is followed or preceded by another pattern, without including that second pattern in the actual match.
Lookaheadsâ
- Positive Lookahead
(?=...): Matches a group only if it is followed by a specific pattern. - Negative Lookahead
(?!...): Matches a group only if it is not followed by a specific pattern.
// Matches 'Java' only if it is followed by 'Script'
const pattern = /Java(?=Script)/;
console.log(pattern.test("JavaScript")); // true
console.log(pattern.test("JavaCoffee")); // false
Lookbehindsâ
- Positive Lookbehind
(?<=...): Matches a group only if it is preceded by a specific pattern. - Negative Lookbehind
(?<!...): Matches a group only if it is not preceded by a specific pattern.
Professional Implementation: Flags and Methodsâ
Regex behavior is modified by flags added to the end of the expression:
g(Global): Finds all matches rather than stopping after the first one.i(Ignore Case): Makes the pattern case-insensitive.m(Multiline): Allows^and$to match the start and end of lines.
Essential JavaScript Methodsâ
regex.test(string): Returns a boolean. Best for simple validation.string.match(regex): Returns an array of matches ornull.string.replace(regex, replacement): Replaces matches with a new string.string.split(regex): Breaks a string into an array using a pattern as the delimiter.
Practical Case: Complex Password Validationâ
To demonstrate the power of combining these concepts, consider a requirement for a password that must contain at least one uppercase letter, one lowercase letter, one digit, and be at least 8 characters long.
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
// Breakdown:
// ^ Start of string
// (?=.*[a-z]) Lookahead: must contain a lowercase letter
// (?=.*[A-Z]) Lookahead: must contain an uppercase letter
// (?=.*\d) Lookahead: must contain a digit
// .{8,} Match at least 8 characters of any type
// $ End of string
Performance Considerationsâ
- Catastrophic Backtracking: Avoid nested quantifiers (e.g.,
(a+)+$) on long strings. This can lead to exponential complexity, causing the browser to hangâa phenomenon known as "Regex Denial of Service" (ReDoS). - Pre-compilation: If you are using a Regex inside a high-frequency loop, define the
RegExpobject outside the loop. This prevents the engine from recompiling the pattern on every iteration. - Readability: For highly complex patterns, use comments or break the Regex into smaller, named parts to ensure the code remains maintainable by other engineers.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Tooling and Performance
Next
Advanced Error Handling
-
Fundamentals and Syntax
- Character Classes and Meta-characters
-
Quantifiers: Controlling Frequency
- Greedy vs. Lazy Matching
-
Anchors and Boundaries
-
Advanced Assertions: Lookaheads and Lookbehinds
- Lookaheads
- Lookbehinds
-
Professional Implementation: Flags and Methods
- Essential JavaScript Methods
-
Practical Case: Complex Password Validation
-
Performance Considerations
