JavaScript Notes
Master JavaScript string replacing: replace(), replaceAll(), regex patterns, capture groups, callback replacer functions, and real-world text transformation examples.
What is String Replacing?
String replacing creates a new string where matched text is swapped out for replacement text. The original string is never changed (immutable).
Think of it like Find & Replace in a word processor — you search for a word and replace it, but JavaScript gives you much more power with regex and callback functions.
replace() — Replace First Match
const sentence = "JavaScript is great. JavaScript is fun.";
const result = sentence.replace("JavaScript", "JS");
console.log(result);
console.log(sentence); // original unchangedJS is great. JavaScript is fun. JavaScript is great. JavaScript is fun.
replace() only replaces the first occurrence when given a plain string.replaceAll() — Replace All Matches (ES2021)
const text = "cat and cat and cat";
const result = text.replaceAll("cat", "dog");
console.log(result);dog and dog and dog
replace() with Regex — Replace ALL (Classic Way)
Using the g (global) flag on a regex is the classic pre-ES2021 way to replace all occurrences:
const message = "Hello World, Hello JavaScript, Hello Students";
// Using regex with g flag — replaces ALL
const result1 = message.replace(/Hello/g, "Hi");
console.log(result1);
// Case-insensitive replace with gi flags
const result2 = message.replace(/hello/gi, "Hey");
console.log(result2);Hi World, Hi JavaScript, Hi Students Hey World, Hey JavaScript, Hey Students
replace() vs replaceAll() — When to Use Which
| Situation | Method | Example |
|---|---|---|
| Replace only FIRST occurrence | replace("old", "new") | Fix one typo |
| Replace ALL (modern code) | replaceAll("old", "new") | Replace all words |
| Replace ALL (older code / pattern) | replace(/pattern/g, "new") | Classic approach |
| Case-insensitive replace | replace(/pattern/gi, "new") | Only regex supports this |
| Pattern-based replace | replace(/regex/, "new") | Complex patterns |
| Replace with dynamic logic | replace(/regex/, fn) | Callback replacer |
Replace with Regex Patterns
Remove all digits
const mixed = "Hello123World456";
const lettersOnly = mixed.replace(/\d/g, "");
console.log(lettersOnly);HelloWorld
Remove all non-alphanumeric characters
Hello World
Replace multiple spaces with one
const text = "Hello World JavaScript";
const normalized = text.replace(/\s+/g, " ");
console.log(normalized);Hello World JavaScript
Replace with Capture Groups
Capture groups (pattern) in regex let you reuse matched parts in the replacement using $1, $2, etc.
// Reformat date from YYYY-MM-DD to DD/MM/YYYY
const isoDate = "2026-06-12";
const formatted = isoDate.replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1");
console.log(formatted);12/06/2026
Pattern: (\d{4}) - (\d{2}) - (\d{2})
Capture: $1 $2 $3
"2026" → $1
"06" → $2
"12" → $3
Replace with: "$3/$2/$1" → "12/06/2026"Swap first and last name
const name = "Sharma, Priya";
const swapped = name.replace(/(\w+),\s(\w+)/, "$2 $1");
console.log(swapped);Priya Sharma
Replace with a Callback Function
The replacement can be a function — called for each match, its return value becomes the replacement.
The Javascript Master Course
Censor specific words
The service was *** and the food was ********
Double all numbers in text
Price: 100, Tax: 20, Discount: 10
Real World Use Cases 🌍
1. Generate URL slug
javascript-master-course-2026 how-to-use-react-nodejs-together
2. Sanitize user input
function sanitizeInput(input) {
return input
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
const userInput = '<script>alert("XSS")</script>';
console.log(sanitizeInput(userInput));<script>alert("XSS")</script>
3. Format phone number
function formatPhone(raw) {
const digits = raw.replace(/\D/g, ""); // remove non-digits
return digits.replace(/(\d{5})(\d{5})/, "$1-$2");
}
console.log(formatPhone("9876543210"));
console.log(formatPhone("+91 98765 43210"));98765-43210 98765-43210
4. Highlight search term in text
function highlight(text, term) {
const regex = new RegExp(`(${term})`, "gi");
return text.replace(regex, "**$1**");
}
console.log(highlight("JavaScript is a scripting language", "script"));Java**Script** is a **script**ing language
Common Mistakes ❌
1. Using replace() to replace all, forgetting it's first-only
// ❌ Wrong — only replaces first "a"
const str = "banana";
console.log(str.replace("a", "o")); // "bonana"
// ✅ Correct — replace all with replaceAll or regex
console.log(str.replaceAll("a", "o")); // "bonono"
console.log(str.replace(/a/g, "o")); // "bonono"2. Mutating the original (forgetting to capture return)
// ❌ Wrong — result discarded
let msg = "Hello World";
msg.replace("World", "JavaScript");
console.log(msg); // "Hello World" — unchanged!
// ✅ Correct — capture the new string
msg = msg.replace("World", "JavaScript");
console.log(msg); // "Hello JavaScript"3. Special characters in replacement string
// ❌ Unexpected: $ has special meaning in replacement
const str = "price: 100";
console.log(str.replace("100", "$50")); // "$50" has special meaning
// In replacement string:
// $& = matched substring
// $1 = first capture group
// $` = text before match
// $' = text after match
// ✅ Escape the $ if you want a literal dollar sign
console.log(str.replace("100", "\\$50")); // "price: $50"Interview Questions 🎯
Q1. What is the difference between replace() and replaceAll()? > replace() replaces only the first occurrence when given a string. replaceAll() replaces all occurrences. To replace all with replace(), use a regex with the g flag.
Q2. How do you make a case-insensitive replacement? > Use a regex with the i flag: str.replace(/pattern/gi, "replacement"). Neither replace() nor replaceAll() with a plain string supports case-insensitivity.
Q3. What are capture groups in replace? > Parentheses (pattern) in regex create capture groups. In the replacement string, $1, $2 refer to what those groups matched. Great for reformatting strings like dates or names.
Q4. How can you use a function as the replacement in replace()? > str.replace(regex, (match, ...groups) => newValue). The function receives the match and capture groups, and its return value is used as the replacement.
Q5. Does replace() mutate the original string? > Never. Strings are immutable. replace() returns a new string. You must assign the result.
Q6. How do you remove all whitespace from a string? > str.replace(/\s+/g, "") removes all whitespace. Or str.replaceAll(" ", "") for only spaces.
Q7. How do you dynamically create a regex for replace? > Use new RegExp(pattern, flags). E.g., new RegExp(word, "gi") creates a case-insensitive global regex from a variable.
Key Takeaways 🏁
replace()replaces only the first match with a plain stringreplaceAll()replaces all matches (ES2021)- Use
replace(/pattern/g, ...)for regex-based replace-all - Capture groups
$1, $2in replacement allow reformatting - Callback function as replacer enables dynamic, logic-based replacement
- All methods return new strings — always capture the return value
- The
iflag makes matching case-insensitive (only in regex, not plain string)
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript String Replacing - replace(), replaceAll() & Regex Patterns Guide.
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, strings, string, replacing
Related JavaScript Master Course Topics