Code Logo

Replace All with RegExp

Published at25 Jul 2026
JavaScript String Handling Medium 0 views
Like0

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

Example 1
Input
"hello world hello","hello","hi"
Output
"hi world hi"
Explanation

Replace all hello with hi

Example 2
Input
"test","t","T"
Output
"TesT"
Explanation

Replace all t with T

Example 3
Input
"aaaa","aa","b"
Output
"bb"
Explanation

Non-overlapping replacement

Example 4
Input
"abc abc abc","abc","x"
Output
"x x x"
Explanation

Replace all abc with x

Example 5
Input
"no match","xyz","a"
Output
"no match"
Explanation

No occurrences to replace

Algorithm Flow

Recommendation Algorithm Flow for Replace All with RegExp
Recommendation Algorithm Flow for Replace All with RegExp

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.

function solution(s) { return s.replace(/foo/g, 'bar'); }

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

javascript - Approach 1
function solution(str, find, replace) {
  var regex = new RegExp(find, 'g');
  return str.replace(regex, replace);
}