RegEx (Regular Expressions)
Q. What is RegEx? A sequence of characters that define a pattern
Q. What is RegEx used for? Validation — search, match, and replace text in strings
Q. How do you implement RegEx in JavaScript?
a) Regular Expression Literal
- The forward slashes delimit the regex
const regExExample = /hello?/;
b) RegExp( ) Constructor function
const text= "hello?";const re = new RegExp(text);
1. Literal Characters
- Purpose: matches the exact characters we want
- Ex. pattern=”Fred” → Fred ✅ , fred ❎
2. Character Class: [ ] , ( )
- Purpose: matches the characters in the brackets

- Ex. pattern=”[fF]red” → Fred ✅ , fred ✅ , fFred ❎
- Ex. pattern=”[5–9]” → matches a single digit from 5 to 9
- Ex. pattern=”(hi!){2}” → hi!hi! ✅
3. Negated Character Class: [ ^]
- Purpose: matches any character EXCEPT the character in the bracket
- Ex. pattern=”p[^ua]” → pi ✅ , po ✅ , pu ❎ , pa ❎
Matches p followed by any single letter except u or a
4. Anchors: ^ , $
- Purpose: matches the string that only has the character(s) we want
NOTE: It accounts for the character(s) and the position

- Ex. pattern=”^dog” → dog hi ✅ , hi dog ❎ , doggy hi ✅
- Ex. pattern=”dog$” → dog hi ❎ , hi dog ✅
- Ex. pattern=”^dog$” → dog ✅ , dog hi ❎ , hi dog ❎
5. Shorthand Character Class: \d, \w, \s, \D, \W, \S, .
- Purpose: matches the characters/digits we want

6. Quantifiers: { } ,* ,+ ,?
- Purpose: concise — no need to repeat same character class when matching 1+

i) { }
- Ex. pattern=”\d{3}” → matches 3 digits
- Ex. pattern=”[A-Z]{1, 5}” → matches between 1 & 5 capital letters
- Ex. pattern=”\d{5, } → matches 5 to an infinite number of digits
ii) *
- Ex. pattern=”ab\d*” → ab ✅ , ab1 ✅ , ab1234 ✅
NOTE: Can be replaced with “ab\d{0, }”
iii) +
- Ex. pattern=”ab\d+” → ab1 ✅ , ab1234 ✅ , ab ❎ , ab1234d ❎
iv) ?
- Ex. pattern=”ab\d?” → ab ✅ , ab1 ✅ , ab1234 ❎
7. Escape Special Characters: \
- Purpose: to include special characters in regex → precede with \ (backslash)
NOTE: No need to escape special character within character class ([ ])
- Ex. pattern=”\{\d,\d}\” → {3,5} ✅ 3,5 ❎
8. Alternation: |
- Purpose: search for one of several characters of words (similar to JS’ ||)
- Ex. pattern=”I have a (dog|cat|bird|fish)./” → I have a dog. ✅ , I have a cat. ✅ , I have a bird. ✅ , I have a fish. ✅
9. Boundary: \b
- Purpose: Search for whole words only
- Ex. pattern=”\bDog\b” → Dog ✅ , Doggy ❎ , My Dog is Sparky ✅
Resources
- Here’s a concise 2-page RegEx cheatsheet I made:
https://docs.google.com/document/d/13Q5Yx_I1YscShFJTqhgA6s4nUnMXc5lVlY0JlcxRu-4/edit?usp=sharing