JavaScript RegExp Complete Guide: Deep Dive into Regular Expressions
JavaScript has built-in powerful regular expression support. This article provides a deep dive into JavaScript's RegExp object, from basic syntax to the latest ES2024 features.
Creating Regular Expressions
JavaScript offers two ways to create regular expressions:
- Literal syntax:
/pattern/flags - Constructor:
new RegExp("pattern", "flags")
Flags
| Flag | Name | Description |
|---|---|---|
g | global | Match all occurrences |
i | ignoreCase | Case-insensitive matching |
m | multiline | ^ and $ match each line |
s | dotAll | Dot matches newlines |
u | unicode | Enable Unicode mode |
v | unicodeSets | ES2024 Unicode sets |
d | hasIndices | Provide match position indices |
y | sticky | Sticky search from lastIndex |
Common Methods
RegExp Methods
- test() — Returns boolean indicating match
- exec() — Returns match array or null
String Methods
- match() — Returns match results array
- matchAll() — Returns iterator of all matches (ES2020)
- replace() / replaceAll() — Replace matched text
- search() — Returns index of first match
- split() — Split string by regex
Named Capture Groups
ES2018 introduced named capture groups (?<name>...), allowing captured content to be accessed by name rather than index, greatly improving code readability.
Lookahead and Lookbehind
| Type | Syntax | Description |
|---|---|---|
| Positive lookahead | (?=...) | Must be followed by pattern |
| Negative lookahead | (?!...) | Must not be followed by pattern |
| Positive lookbehind | (?<=...) | Must be preceded by pattern |
| Negative lookbehind | (?<!...) | Must not be preceded by pattern |
ES2024 Feature: The v flag (unicodeSets) brings set operations to character classes, including intersection (&&) and subtraction (--), making Unicode character handling more flexible.
Test Your Regular Expressions
Try the Regex Tester Tool →Conclusion
JavaScript's regex capabilities continue to grow with each ECMAScript release. Mastering these features helps you handle text processing tasks more efficiently.
References
- ECMA International. "ECMAScript Language Specification — RegExp." ECMA-262. https://tc39.es/ecma262/#sec-regexp-regular-expression-objects
- Mozilla Developer Network. "RegExp." MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
- TC39. "TC39 Proposals." GitHub. https://github.com/tc39/proposals