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", ""]