Table of contents
javascript regex
methods
create regex
var regex = /.+/;
var regex = new RegExp('.+');
create regex with flags
var regex = new RegExp('[0-9]+', 'g');
var regex = /[0-9]+/g;
check if string matches regex (use ^...$ to match whole string)
var bool = regex.test(string);
find match
var myArray = regex.exec('[input]');
find index of first match
string.search(regex);
get matching groups
var myArray = string.match(/pattern/);
multimatch
var iterator = string.match(/pattern/g);
var iterator = string.matchAll(/pattern/);
do {
var current = iterator.next();
current.done || console.log(current.value);
} while (!current.done)
regex replace
string.replace(regex, '[replace]');
string.replaceAll(regex, '[replace]');
watch out: literal string replace
string.replace('find literal string', '[replacement]');
regex split
string.split(regex);
regex syntax
available flags
i = case insensitive
g = general search (all matches)
m = multiline mode
s = dot '.' matches '\n'
u = unicode support
y = sticky (exact position match)
escape sequences
\\ = backslash
\. = literal dot '.'
\t = tab
\r = carriage return
\n = newline
\u[code] = unicode code point in hex
meta characters
. = any character
^ = begin of input
$ = end of input
\b = word boundary
\B = not a word boundary
\d = digit
\D = not a digit
\s = whitespace
\S = not whitespace
\w = word
\W = not a word character
repetition
? = optional character, greedy
?? = optional character, lazy
* = zero or more characters, greedy
*? = zero or more characters, lazy
+ = one or more characters, greedy
+? = one or more characters, lazy
{N} = exactly N characters
{N,} = N or more characters, greedy
{N,}? = N or more characters, lazy
{N,M} = N to M characters, greedy
{N,M}? = N to M characters, lazy
groups
() capturing group
(?<Name>x) named capturing group
(?:x) non-capturing group
\[1-9] backreference
\k[name] backreference to named group
lookahead & lookbehind
(?= ... ) lookahead
(?! ... ) negative lookahead
(?<= ... ) lookbehind
(?<! ... ) negative lookbehind
examples
all input
/.+/
everything up until the last slash in string
/.*[/]/
documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
https://javascript.info/regular-expressions