DEV Community

Volodyslav
Volodyslav

Posted on

RegEx cheat sheet for JavaScript

Hello, guys! Today, I've prepared a Regular expression(RegEx) cheat sheet for JavaScript.😊

Basic Patterns:
/abc/- Literal characters match themselves.
/./ - Matches any character except a newline.
/\d/ - Matches a digit (0-9).
/\D/ - Matches a non-digit.
/\w/ - Matches a word character (alphanumeric and underscore).
/\W/ - Matches a non-word character.
/\s/ - Matches a whitespace character.
/\S/ - Matches a non-whitespace character.

Quantifiers:
/*/ - Matches 0 or more of the preceding element.
/+/ - Matches 1 or more of the preceding element.
/?/ - Matches 0 or 1 of the preceding element.
/{n}/ - Matches exactly n of the preceding element.
/{n,}/ - Matches n or more of the preceding element.
/{n,m}/ - Matches between n and m of the preceding element.

Anchors:
/^/ - Matches the start of a string.
/$/ - Matches the end of a string.
/\b/ - Matches a word boundary.

Character Classes:
/[abc]/ - Matches any one of the characters a, b, or c.
/[^abc]/ - Matches any character except a, b, or c.
/[a-z]/ - Matches any lowercase letter.
/[A-Z]/ - Matches any uppercase letter.
/[0-9]/ - Matches any digit.

Grouping and Alternation:
/(abc)/ - Groups patterns together.
/a|b/ - Matches a or b.

Modifiers:
/i - Case-insensitive matching.
/g - Global matching (find all matches).
/m - Multiline matching.

Escaping Special Characters:
/./ - Matches a literal period (dot).
/ \\ / - Matches a literal backslash.

Quantifier Shortcuts:
/*/ - Equivalent to {0,}.
/+/ - Equivalent to {1,}.
/?/ - Equivalent to {0,1}.

Functions:
test() - Tests if a regex pattern matches a string.
exec() - Searches for a pattern in a string and returns the first match.
match() - Returns an array of all matches.
search() - Searches for a pattern and returns the index of the first match.
replace() - Replaces matches with a specified string.
split() - Splits a string into an array based on a pattern.

Example:

let text = "Coding is Fun, very Fun, extremely fun";
let pattern = /fun/ig;
let matches = text.match(pattern); // Returns an array of matches = [ 'Fun', 'Fun', 'fun' ]
let searchIndex = text.search(pattern); // Returns the index of the first match = 10
let replacedText = text.replace(pattern, 'cool'); // Replaces matches with 'cool' = Coding is cool, very cool, extremely cool
let parts = text.split(pattern); // Splits the string into an array based on matches = [ 'Coding is ', ', very ', ', extremely ', '' ]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)