This was originally posted as a twitter thread: https://twitter.com/chrisachard/status/1181583499112976384
In JavaScript they’re created in between forward slashes //, or with new RegExp()
and then used in methods like match
, test
, or replace
You can define the regex beforehand, or directly when calling the method
or put multiple characters in square brackets [] to capture any that match
Capture a range of characters with a hyphen -
In JavaScript, these flags are:
i = case insensitive
m = multi line matching
g = global match (find all, instead of find one)
Using a dollar sign $ at the end means “end of string”
Start putting groups of matches together to match longer strings
. = any character except line break
\d = digit
\D = NOT a digit
\s = white space
\S = any NON white space
\n new line
match
will return the full match plus the groups, unless you use the g
flag
Use the pipe operator | inside of parens () to specify what that group matches
| = or
Special characters in JS regex are: ^ $ \ . * + ? ( ) [ ] { } |
So to match an asterisks, you’d use:
*
Instead of just *
This means ^ has two meanings, which can be confusing.
It means both “start of string” when it is at the front of a regex, and “not this character” when used inside of square brackets.
HOWEVER! be careful if you try to use regexs for really complex tasks, such as parsing emails (which get really confusing, really fast), or HTML (which is not a regular language, and so can’t be fully parsed by a regular expression)
There is (of course) much more to regex like lazy vs greedy, lookahead, and capturing
but most of what web developers want to do with regular expressions can use just these base building blocks.
#javascript #web-development #regex