Problem Statement
How many occurrences does replace() replace by default?
Explanation
The replace method only replaces the first occurrence of the search string.
To replace all occurrences, use replaceAll or a regular expression with the global flag.
Replace returns a new string without modifying the original.
The search value can be a string or regular expression.
The replacement value can be a string or function.
This is a common gotcha in JavaScript interviews.
Code Solution
SolutionRead Only
const str = 'hello hello hello';
// replace() - only first occurrence
const replaced = str.replace('hello', 'hi');
console.log(replaced); // 'hi hello hello'
// replaceAll() - all occurrences (ES2021)
const allReplaced = str.replaceAll('hello', 'hi');
console.log(allReplaced); // 'hi hi hi'
// Using regex with global flag
const regexReplace = str.replace(/hello/g, 'hi');
console.log(regexReplace); // 'hi hi hi'
// Case-insensitive replace
const text = 'Hello HELLO hello';
const caseInsensitive = text.replace(/hello/gi, 'hi');
console.log(caseInsensitive); // 'hi hi hi'
// Replace with function
const numbers = 'I have 2 apples and 3 oranges';
const doubled = numbers.replace(/\d+/g, (match) => {
return match * 2;
});
console.log(doubled); // 'I have 4 apples and 6 oranges'
// Remove all spaces
const spaced = 'H e l l o';
console.log(spaced.replace(/\s/g, '')); // 'Hello'
// Replace with captured groups
const date = '2024-01-15';
const formatted = date.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/$1');
console.log(formatted); // '15/01/2024'
// Common mistake
const wrong = 'aaa'.replace('a', 'b');
console.log(wrong); // 'baa' (not 'bbb'!)