Regex Cheat Sheet for JavaScript

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

SyntaxDescriptionExample
.Matches any character except newline/he.t/ matches “heat” or “hiet”
\dMatches a digit (0-9)/\d/ matches “2” in “a2b”
\DMatches a non-digit character/\D/ matches “a” in “a2b”
\wMatches a word character (a-z, A-Z, 0-9, _)/\w/ matches “a” in “a2b”
\WMatches a non-word character/\W/ matches ” ” in “a 2b”
\sMatches whitespace (space, tab, newline)/\s/ matches ” ” in “a b”
\SMatches non-whitespace character/\S/ matches “a” in “a b”

Quantifiers

SyntaxDescriptionExample
*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

SyntaxDescriptionExample
^Start of the string/^he/ matches “hello” but not “ahello”
$End of the string/he$/ matches “che” but not “chess”
\bWord boundary/\bhe/ matches “he” in “hello” but not in “the”

Groups and Ranges

SyntaxDescriptionExample
()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

FlagDescriptionExample
iCase-insensitive match/he/i matches “He”, “HE”
gGlobal match/he/g finds all occurrences in the string
mMultiline mode/^he/m matches “he” at the start of each line
sDot 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

  1. Use comments: Break down complex regex patterns for better readability.
  2. Test thoroughly: Use tools like regex testers to ensure your patterns work as expected.
  3. Keep it simple: Avoid overcomplicating patterns; start simple and build up.
  4. Use the global flag: When searching for multiple matches, don’t forget the g flag.
  5. Be mindful of performance: Complex patterns can be slow, especially with large strings.

Common Mistakes

  1. Forgetting to escape: Characters like . and $ have special meanings; escape them with \ if you want to match them literally.
  2. Overusing .*: This can lead to unexpected matches; be specific with your patterns.
  3. Ignoring edge cases: Always test with different inputs, including edge cases like empty strings or strings with special characters.
  4. 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.

Index
Scroll to Top