Question:

What is the key difference between the JavaScript string methods replace() and replaceAll()? Support your answer with an example.

Show Hint

Warning! If you pass a regular expression to replaceAll(), it must contain the global (/g) flag. If the global flag is missing, JavaScript will throw a TypeError: replaceAll must be called with a global RegExp.
Updated On: Jun 29, 2026
Show Solution
collegedunia
Verified By Collegedunia

Solution and Explanation



Step 1: Analyzing the replace()
Method:
The replace() method is used to search a string for a specified substring value (or regular expression) and return a new string with the replacement applied.
Scope Limitation: If a simple string is passed as the search target (not a regular expression), replace() only replaces the very first occurrence of that search string. Any subsequent identical substrings inside the parent string are ignored.

Step 2: Analyzing the replaceAll()
Method:
The replaceAll() method (introduced in ECMAScript 2021) is designed to replace all occurrences of a specified substring with a new value.
Global Scope: Unlike replace(), passing a plain string to replaceAll() replaces every single matching instance throughout the string, without needing a global regular expression.

Step 3: Demonstration with a Code Example:

Let's see how both methods handle the same source string: var original = "apple banana apple grape"; // 1. Using replace() var replaceResult = original.replace("apple", "orange"); console.log(replaceResult); // Output: "orange banana apple grape" (Only the FIRST "apple" changed) // 2. Using replaceAll() var replaceAllResult = original.replaceAll("apple", "orange"); console.log(replaceAllResult); // Output: "orange banana orange grape" (ALL occurrences of "apple" changed)
Was this answer helpful?
0
0