regular expressions in javascript
TRANSCRIPT
Constructor
new RegExp('ab+c', 'i');new RegExp(/ab+c/, 'i');Don't forget the normal string escape rules for special characters!
An object with information about the match
/abc/.exec("defabcde").index;=> 3/abcff/.exec("defabcde").index;=> null
Brackets
[abc] - Matches any single character a, b, or c[^abc] - Matches any character except a, b, c[a-c] - Matches any character from a to c
Character Classes
\w - Alphanumeric (word) character\W - Non-alphanumeric character\s - Whitespace character\S - Non-whitespace character
No love for non-Latin characters"éβ".search(/\w/);=> -1Try xRegExp or defining word characters using Unicode.
Boundaries
^ - Start of line$ - End of line\b - At beginning or end of word\B - Not at beginning or end of word
Quantifiers
n{3} - Match sequence of 3 n'sn{3,5} - Match sequence of 3 to 5 n'sn{3,} - Match sequence of 3 or more n's
Assertions
x(?=y) - Matches x only if x is followed by yx(?!y) - Matches x only if x is not followed by y
Capture Groups
"Hopper, Grace\nLovelace, Ada".replace(/([\w ]+), ([\w ]+)/g, "$2 $1");
=> "Grace Hopper Ada Lovelace"
Greedy Operators + * ? {}
/<.+>/.exec("<p>Hello world</p>");=> "<p>Hello world</p>"/<.+?>/.exec("<p>Hello world</p>");=> "<p>"
Help!
scriptular.comMDN | Regular Expressionsregexr.com