GGistDev

RegExp in JavaScript

Regular expressions support powerful pattern matching and replacement.

Literals and flags

/abc/i       // case-insensitive
new RegExp('a+b', 'g')

Common flags: i ignore case, g global, m multiline, s dotAll, u Unicode, y sticky.

Testing and exec

/\d+/.test('a1b')        // true
const m = /([A-Z])(\d+)/.exec('A12')
m[0], m[1], m[2]

String.match/matchAll integrate with regex.

'a1 b22'.match(/\d+/g)           // ['1','22']
[... 'a1 b22'.matchAll(/\d+/g)]  // iterator of matches

Groups and named groups

const m2 = /(?<let>[A-Z])(?<num>\d+)/.exec('B99')
m2.groups.let, m2.groups.num

Replace and split

'a b  c'.replace(/\s+/g, ' ')          // 'a b c'
'a1 b2'.replace(/\d+/g, m => Number(m) * 2) // 'a2 b4'
'a,b; c'.split(/[;,]\s*/)

Lookaround and lazy

/(?<=\$)\d+/.test('$10')
'<a><b>'.match(/<.+?>/)  // ['<a>']

Unicode and escapes

Use u flag for proper Unicode escapes and code points.

'\u{1F680}'.match(/\u{1F680}/u)

Escaping user input

function escapeRe(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') }

Performance tips

Precompile reused regexes; avoid catastrophic backtracking; keep patterns specific.

Summary

  • Use literals/flags; test with .test/.exec/match(All)
  • Groups, lookaround, and lazy quantifiers enable powerful matches
  • Escape inputs and prefer Unicode-aware patterns (u)