J

JavaScript Handbook

Clean • Professional

Regular Expressions (RegEx) in JavaScript

2 minute

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

FlagMeaning
gGlobal search (find all matches)
iCase-insensitive search
mMulti-line search
sDot matches newline
uUnicode mode
ySticky search (match from index)
const regex = /hello/gi;

Basic Patterns

PatternDescriptionExample
.Any single character/h.t/ → matches "hat", "hit"
\\dDigit (0-9)/\\d/ → matches "3"
\\DNon-digit/\\D/ → matches "a"
\\wWord character (a-z, A-Z, 0-9, _)/\\w/ → matches "a"
\\WNon-word character/\\W/ → matches "!"
\\sWhitespace/\\s/ → matches " "
\\SNon-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

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

 

Article 0 of 0