JavaScript Notes
Learn JavaScript regular expressions from scratch: regex syntax, test(), match(), replace(), split(), literal and constructor forms, and interview Q&A. beginner-friendly.
Regular expressions (regex) are patterns used to match, search, and manipulate text. They are one of the most powerful tools in a developer's toolkit — used for validation, parsing, search-and-replace, and data extraction.
JavaScript has built-in regex support through the RegExp class and special syntax (/pattern/flags).
📊 Regex Pattern Anatomy
💻 Example 1 — Creating Regex: Literal vs Constructor
// Literal syntax (preferred for static patterns)
const literal = /javascript/i;
// Constructor syntax (for dynamic patterns)
const keyword = "javascript";
const dynamic = new RegExp(keyword, "i");
console.log(literal.test("Learn JavaScript today!"));
console.log(dynamic.test("Learn JavaScript today!"));
// Constructor needed when pattern comes from a variable
function searchPattern(text, word) {
const pattern = new RegExp(`\\b${word}\\b`, "gi"); // word boundary
return text.match(pattern);
}
console.log(searchPattern("JavaScript is great. JS is javascript!", "javascript"));true true [ 'JavaScript', 'javascript' ]
💻 Example 2 — test(), match(), replace(), split(), search()
const text = "My phone: +91-9876543210, email: riya@wohotech.in";
// .test() — returns boolean
console.log(/\d+/.test(text)); // true — contains digits
// .match() — returns matched array
console.log(text.match(/\d+/g)); // all digit groups
// .replace() — replace matches
console.log(text.replace(/\d/g, "*")); // mask all digits
// .split() — split on pattern
const csv = "Riya, Aman, Priya , Raj";
console.log(csv.split(/\s*,\s*/)); // split by comma + optional spaces
// .search() — returns index of first match (-1 if not found)
console.log(text.search(/@/)); // position of @
console.log(text.search(/xyz/)); // -1 — not foundtrue [ '91', '9876543210' ] My phone: +**-**********, email: riya@wohotech.in [ 'Riya', 'Aman', 'Priya', 'Raj' ] 37 -1
💻 Example 3 — Anchors: ^ and $
// ^ matches start of string
// $ matches end of string
const exactHello = /^hello$/i;
console.log(exactHello.test("hello")); // true
console.log(exactHello.test("say hello")); // false — not start
console.log(exactHello.test("hello world")); // false — not end
console.log(exactHello.test("HELLO")); // true — i flag ignores case
// Start anchor only
const startsWithJS = /^js/i;
console.log(startsWithJS.test("JavaScript")); // true
console.log(startsWithJS.test("Learn JS")); // false
// End anchor only
const endsWithDotCom = /\.com$/i;
console.log(endsWithDotCom.test("wohotech.in")); // true
console.log(endsWithDotCom.test("wohotech.in")); // falsetrue false false true true false true false
💻 Example 4 — Special Characters: . \d \w \s and Their Negations
[ true, false, false, true ] 12 hello_123 trim me true true false
📋 Common Regex Special Characters
| Character | Meaning | Example | Matches |
|---|---|---|---|
. | Any character (except newline) | /a.c/ | "abc", "aXc" |
^ | Start of string | /^hi/ | "hi there" |
$ | End of string | /bye$/ | "say bye" |
\d | Digit [0-9] | /\d+/ | "42" |
\D | Non-digit | /\D+/ | "abc" |
\w | Word char [a-zA-Z0-9_] | /\w+/ | "hello_1" |
\W | Non-word char | /\W/ | "!", " " |
\s | Whitespace | /\s+/ | " ", "\t" |
\S | Non-whitespace | /\S+/ | "hello" |
\b | Word boundary | /\bjava\b/i | "Java" not "JavaScript" |
\ | Escape special char | /\./ | literal . |
⚠️ Common Mistakes
❌ Mistake 1 — Forgetting to Escape Dots in Domains
// BAD — . matches ANY character
const bad = /wohotech.in/;
console.log(bad.test("wohoteChXin")); // true! . matched any char
// GOOD — escape the dot
const good = /wohotech\.in/;
console.log(good.test("wohoteChXin")); // false
console.log(good.test("wohotech.in")); // truetrue false true
❌ Mistake 2 — Missing g Flag in .replace() for All Occurrences
const text = "apple apple apple";
console.log(text.replace(/apple/, "mango")); // only first replaced!
console.log(text.replace(/apple/g, "mango")); // all replacedmango apple apple mango mango mango
❌ Mistake 3 — Using Regex When String Methods Are Simpler
🎯 Key Takeaways
- A regex is a pattern that describes text shapes — not fixed strings
- Two ways to create: literal
/pattern/flags(preferred) ornew RegExp(str, flags)(for dynamic patterns) - Key methods:
test()(boolean),match()(array),replace(),split(),search()(index) - Anchors
^and$pin the pattern to the start/end of the string \d,\w,\sare shorthand classes; uppercase versions (\D,\W,\S) are their negations- Always escape special characters with
\when you want them literal:\.,\*,\(
❓ Interview Questions
Q1. What is a regular expression in JavaScript? > A regular expression is a pattern that describes the structure of text. JavaScript implements them as RegExp objects. You use them to test if text matches a pattern, extract matches, or replace matched text.
Q2. What is the difference between /pattern/ and new RegExp("pattern")? > Literal /pattern/ is compiled at parse time — best for static patterns. new RegExp(str) is compiled at runtime — required when the pattern is built from a variable. Note: in string form, \d must be written as \\d since backslash is a string escape character.
Q3. What does test() return vs match()? > test() returns a boolean — true if the pattern matches. match() is called on a string and returns an array of matches (or null if no match). With the g flag, match() returns all matches; without g, it returns the first match with capture group details.
Q4. What is the difference between ^ inside and outside []? > Outside [], ^ is a start-of-string anchor: /^hello/ matches strings starting with "hello". Inside [], ^ negates the class: /[^0-9]/ matches any character that is NOT a digit.
Q5. What is \b in regex? > \b is a word boundary — a zero-width assertion matching the position between a word character (\w) and a non-word character. /\bjava\b/i matches "Java" as a standalone word but not in "JavaScript".
Q6. How do you make a regex case-insensitive? > Add the i flag: /hello/i matches "hello", "Hello", "HELLO". Works for both literal and constructor form: new RegExp("hello", "i").
**Q7. What is the difference between + and * in regex?** > + means "one or more" — the character must appear at least once. * means "zero or more" — the character can be absent entirely. /\d+/ requires at least one digit; /\d*/ matches even empty string.
Q8. How does replace() work with a regex? > str.replace(regex, replacement) replaces the first match (or all matches with g flag). The replacement can be a string (use $1, $2 for capture groups) or a function (match, p1, p2, ...) for dynamic replacements.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Regex Basics – Regular Expressions Tutorial for Beginners.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, regex, basics, javascript regex basics – regular expressions tutorial for beginners
Related JavaScript Master Course Topics