Regular Expressions

Regular expressions (regex) are patterns used to match character combinations in strings.

Creating Regex

// Literal
const re1 = /hello/

// Constructor
const re2 = new RegExp('hello')

Flags

FlagMeaning
gGlobal — find all matches
iCase-insensitive
mMultiline — ^ and $ match line start/end
sDotall — . matches newline

Special Characters

^     // start of string
$     // end of string
.     // any character except newline
*     // 0 or more repetitions
+     // 1 or more repetitions
?     // 0 or 1 repetition
\d    // digit [0-9]
\w    // word character [a-zA-Z0-9_]
\s    // whitespace
[abc] // character class: a, b, or c

Methods

const str = 'Hello World 123'

/World/.test(str)            // true
str.match(/\d+/)             // ['123']
str.match(/\w+/g)            // ['Hello', 'World', '123']
str.replace(/World/, 'JS')   // 'Hello JS 123'
str.search(/\d+/)            // 12 (index)
'a,b,,c'.split(/,+/)         // ['a', 'b', 'c']