Regular expressions (regex) are powerful tools for pattern matching and text manipulation. This cheat sheet provides a quick reference guide for common regex operations in JavaScript.
Basic Syntax
Syntax | Description | Example |
---|---|---|
. | Matches any character except newline | /he.t/ matches “heat” or “hiet” |
\d | Matches a digit (0-9) | /\d/ matches “2” in “a2b” |
\D | Matches a non-digit character | /\D/ matches “a” in “a2b” |
\w | Matches a word character (a-z, A-Z, 0-9, _) | /\w/ matches “a” in “a2b” |
\W | Matches a non-word character | /\W/ matches ” ” in “a 2b” |
\s | Matches whitespace (space, tab, newline) | /\s/ matches ” ” in “a b” |
\S | Matches non-whitespace character | /\S/ matches “a” in “a b” |
Quantifiers
Syntax | Description | Example |
---|---|---|
* | Zero or more occurrences | /he*/ matches “he”, “hee”, “heee” |
+ | One or more occurrences | /he+/ matches “hee”, “heee” but not “he” |
? | Zero or one occurrence | /he?/ matches “he” or “hee” |
{n} | Exactly n occurrences | /he{2}/ matches “hee” |
{n,} | At least n occurrences | /he{2,}/ matches “hee”, “heee” |
{n,m} | Between n and m occurrences | /he{2,4}/ matches “hee”, “heee”, “heeee” |
Anchors
Syntax | Description | Example |
---|---|---|
^ | Start of the string | /^he/ matches “hello” but not “ahello” |
$ | End of the string | /he$/ matches “che” but not “chess” |
\b | Word boundary | /\bhe/ matches “he” in “hello” but not in “the” |
Groups and Ranges
Syntax | Description | Example |
---|---|---|
() | Capturing group | /he(l|p)/ matches “help” or “help” |
(?:) | Non-capturing group | /he(?:l|p)/ matches “help” or “help” without capturing |
[] | Character set | /[aeiou]/ matches any vowel |
[^] | Negated character set | /[^aeiou]/ matches any non-vowel |
- | Range within a character set | /[a-z]/ matches any lowercase letter |
Flags
Flag | Description | Example |
---|---|---|
i | Case-insensitive match | /he/i matches “He”, “HE” |
g | Global match | /he/g finds all occurrences in the string |
m | Multiline mode | /^he/m matches “he” at the start of each line |
s | Dot matches newline | /he.s/g matches across newlines |
Common Use Cases
Email Validation
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\. [a-zA-Z]{2,}$/;
console.log(emailRegex.test("[email protected]")); // true
URL Extraction
const urlRegex = /https?:\/\/(www\.)?[a-zA-Z0-9- .]+\.[a-zA-Z]{2,}(\/[a-zA-Z0-9?&=%#-.]*)?/g;
const text = "Visit my website: https://www.example.com and https://example.org";
const urls = text.match(urlRegex);
console.log(urls); // ["https://www.example.com", "https://example.org"]
Date Matching
const dateRegex = /\d{4}-\d{2}-\d{2}/;
console.log(dateRegex.test("2023-10-05")); // true
Phone Number Matching
const phoneRegex = /\(\d{3}\) \d{3}-\d{4}/;
console.log(phoneRegex.test("(123) 456-7890")); // true
Tips and Best Practices
- Use comments: Break down complex regex patterns for better readability.
- Test thoroughly: Use tools like regex testers to ensure your patterns work as expected.
- Keep it simple: Avoid overcomplicating patterns; start simple and build up.
- Use the global flag: When searching for multiple matches, don’t forget the
g
flag. - Be mindful of performance: Complex patterns can be slow, especially with large strings.
Common Mistakes
- Forgetting to escape: Characters like
.
and$
have special meanings; escape them with\
if you want to match them literally. - Overusing
.*
: This can lead to unexpected matches; be specific with your patterns. - Ignoring edge cases: Always test with different inputs, including edge cases like empty strings or strings with special characters.
- Not using the global flag: Missing the
g
flag can cause your regex to stop after the first match.
Frequently Asked Questions
1. How do I match a literal dot in regex?
To match a literal dot, you need to escape it with a backslash: \.
2. How do I make the regex case-insensitive?
Add the i
flag to the regex: /pattern/i
3. How do I match the start or end of a string?
Use ^
for the start and $
for the end of the string.
4. How do I match a specific range of characters?
Use a character set with -
to denote a range: /[a-z]/
matches any lowercase letter.
5. How do I capture groups in regex?
Use parentheses ()
to create capturing groups. For example: /he(l|p)/
captures either “l” or “p”.
6. How do I match multiple occurrences of a pattern?
Use quantifiers like *
, +
, ?
, or {n,m}
. For example: /he+/
matches one or more “e”s after “h”.
Conclusion
Regular expressions are a powerful tool for text manipulation and pattern matching in JavaScript. This cheat sheet provides a quick reference guide for common regex operations. Practice regularly to become more comfortable with regex, and don’t hesitate to use online tools and resources to test and refine your patterns.