Replace All with RegExp
Write a JavaScript function that replaces all occurrences of a substring in a given string using String.replace() with a global regular expression. The function takes three parameters: the original string, the substring to find, and the replacement string.
JavaScript's String.replace() only replaces the first occurrence when given a string as the search value. To replace all occurrences, you must use a regular expression with the global (g) flag. Create a RegExp object using the RegExp constructor: new RegExp(find, 'g'). This dynamically builds a regex from the search string, escaping any special regex characters.
Regular expressions in JavaScript are powerful pattern-matching tools. Using the RegExp constructor allows runtime creation of patterns from string variables. The global flag ensures all matches are replaced, not just the first one. The replace method accepts both string and regex patterns, making it versatile for different replacement scenarios.
Time complexity is O(n * m) where n is the string length and m is the search pattern complexity. The regex engine scans the string for matches. Space complexity is O(n) for the result string. For simple substring replacements, this approach is efficient and idiomatic in JavaScript.
Edge cases include substrings with special regex characters (like . or *), empty search string, overlapping matches, and cases where the replacement string itself contains special characters.
Example Input & Output
Replace all hello with hi
Replace all t with T
Non-overlapping replacement
Replace all abc with x
No occurrences to replace
Algorithm Flow

Solution Approach
Replace all occurrences of a pattern in a string using replace() with a global regex. The g flag ensures all matches are replaced, not just the first. Without the global flag, only the first match is replaced.
For replacing all occurrences of a literal string, replaceAll() is available in modern JavaScript. With regex patterns, capture groups can be referenced: 'hello'.replace(/(l)/g, '-$1-').
Time O(n), Space O(n).
Best Answers
function solution(str, find, replace) {
var regex = new RegExp(find, 'g');
return str.replace(regex, replace);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
