Index

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
var success = string.match(regex);
find match
var myArray = regex.exec('[input]');
find index of first match
string.search(regex);
regex replace
string.replace(regex, '[replace]');
watch out: literal string replace
string.replace('find literal string', '[replacement]');

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

examples

all input
/.+/
everything up until the last slash in string
/.*[/]/
documentation
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
https://javascript.info/regular-expressions