📖 JavaScript Regular Expressions

Regular Expression Object: RegExp

Regular expressions are used to perform powerful pattern-matching and "search-and-replace" functions on text. A regular expression object describes a pattern of characters. When you search in a text, you can use a pattern to describe what you are searching for. A simple pattern can be one single character or a more complicated pattern can consist of more characters, and can be used for parsing, format checking, substitution and more.

/* validEmail validates an email address against a regular expression and returns true or false */
function validEmail(email) {
    var emailRegex = /[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
    var valid = email.match(emailRegex);
    return valid;
}
Regular Expressions
Regular Expression Flags
i Case Insensitive
g Global (all matches)
Regular Expression Character Positions
^ beginning of the text string
$ end of the text string
\b presence of a word boundary
\B absence of a word boundary
Regular Expression Character Classes
\d digit (0-9)
\D non-digit
\w word character (a-z, A-Z, 0-9, _)
\W non-word character (special characters)
\s white-space character (blank space, tab, newline, carriage return, or formfeed
\S non-white spce character
. any character
[chars] match any character in the list of characters chars
[^chars] match any character not in the list of characters chars
[char1-charN] match any character in the range char1 - charN
[^char1-charN] match any character not in the range char1 - charN
[a-z] match lowercase letters
[A-Z] match uppercase letters
[a-zA-Z] match letters (uppercase or lowercase)
[0-9] match digits
Repetition Characters
* Repeat 0 or more times
? Repeat 0 or 1 time
+ Repeat 1 or more times
{n} Repeat exactly n times
{n,} Repeat at least n times
{n,m} Repeat at least n times but no more than m times
Escape Sequences
\/ /
\\ \
\. .
\* *
\+ +
\? ?
\| |
\(\) ()
\{\} {}
\^ ^
\$ $
\n new line
\r carriage return
\t tab
Regular Expression Methods
string.match(re) performs a pattern match on string against the regular expression re; returns true or false
string.match(re/g) returns an array of all matched text
string.replace(re,'newtext') replaces any text within the string string that matches the regular expression re with the string supplied in newtext
Useful Regular Expressions
U.S. Zip Code \d{5}(-\d{4})?
U.S. Phone Number \(?(\d{3})\)?[ -.](\d{3})[ -.](\d{4})
Email address [-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}
Date ([01]?\d)[-\/ .]([123]?\d)[-\/ .](\d{4})
Web address ((\bhttps?:\/\/)|(\bwww\.))\S*