Regular Expressions (RegEx) in JavaScript
A regular expression is a pattern used to match, search, and manipulate strings. They are extremely powerful for validation, parsing, and text processing.
Creation of Regular Expressions
There are two ways to create a RegEx in JavaScript:
Using a Regex Literal (preferred for static patterns):
const regex = /abc/;
Using the RegExp Constructor (useful for dynamic patterns):
const regex = new RegExp("abc");
Flags
| Flag | Meaning |
|---|---|
| g | Global search (find all matches) |
| i | Case-insensitive search |
| m | Multi-line search |
| s | Dot matches newline |
| u | Unicode mode |
| y | Sticky search (match from index) |
const regex = /hello/gi;
Basic Patterns
| Pattern | Description | Example |
|---|---|---|
. | Any single character | /h.t/ β matches "hat", "hit" |
\\d | Digit (0-9) | /\\d/ β matches "3" |
\\D | Non-digit | /\\D/ β matches "a" |
\\w | Word character (a-z, A-Z, 0-9, _) | /\\w/ β matches "a" |
\\W | Non-word character | /\\W/ β matches "!" |
\\s | Whitespace | /\\s/ β matches " " |
\\S | Non-whitespace | /\\S/ β matches "a" |
^ | Start of string | /^a/ β "apple" |
$ | End of string | /a$/ β "pizza" |
[] | Character set | /[aeiou]/ β matches vowels |
| ` | ` | OR |
? | Optional (0 or 1) | /colou?r/ β matches "color" or "colour" |
* | 0 or more times | /a*/ β matches "", "a", "aa" |
+ | 1 or more times | /a+/ β matches "a", "aa" |
{n} | Exactly n times | /a{2}/ β matches "aa" |
{n,} | n or more times | /a{2,}/ β "aa", "aaa" |
{n,m} | Between n and m times | /a{2,3}/ β "aa" or "aaa" |
Methods Using RegEx
| Method | Description |
|---|---|
test() | Returns true if pattern exists in string |
exec() | Returns matched result or null |
match() | String method β returns matches |
matchAll() | Returns all matches with capture groups (ES2020+) |
replace() | Replaces matches with a replacement string |
search() | Returns index of first match |
split() | Splits string by pattern |
Examples:
const str = "Hello123";
// test()
const regex = /\d+/;
console.log(regex.test(str)); // true
// exec()
console.log(regex.exec(str)); // ["123"]
// match()
console.log(str.match(/\d+/)); // ["123"]
// replace()
console.log(str.replace(/\d+/, "456")); // "Hello456"
// search()
console.log(str.search(/\d+/)); // 5
// split()
console.log(str.split(/\d+/)); // ["Hello", ""]Β
