Given a String, and Substring, the task is to replace all occurrences of a substring within a string in JavaScript. This operation is useful for modifying text, formatting text, or processing user input.
Examples
Input: str = "Hello world!",
Replace String 'o' with new String 'x'
Output: Hellx wxrld!
Input: str = "JavaScript Program: JavaScript is a scripting language",
Replace String "JavaScript" with new String "JS"
Output: JS Program: JS is a Scripting language
Approach 1: Using split() and join() Method
The split() method splits the string into an array based on the substring, and then join the array back into a string using a different substring as a delimiter.
const str = "Hello world!"; const replacedStr = str.split("o").join("x"); console.log(replacedStr);
Output:
Hellx wxrld!
Approach 2: Using replace() Method with Regular Expression
The replace() method in JavaScript can accept regular expressions. By using a global regular expression with the g
flag, you can replace all occurrences of a substring within a string.
const str = "Hello world!"; const replacedStr = str.replace(/o/g, "x"); console.log(replacedStr);
Output:
Hellx wxrld!
Approach 3: Using replaceAll() Method (ES2021)
Introduced in ECMAScript 2021 (ES12), the replaceAll() method provides a simple way to replace all occurrences of a substring within a string without using regular expressions.
const str = "Hello world!"; const replacedStr = str.replaceAll("o", "x"); console.log(replacedStr);
Output:
Hellx wxrld!
Approach 4: Using split() and join() Method with Template Literals
With the advent of template literals in ES6, you can also use them in conjunction with split()
and join()
for a concise way to replace all occurrences of a substring.
const str = "Hello world!"; const replacedStr = `${str}`.split("o").join("x"); console.log(replacedStr);
Output:
Hellx wxrld!
Approach 5: Using a Custom Function
For more complex replacements or scenarios where regular expressions may not suffice, you can create a custom function to replace all occurrences of a substring within a string.
function replaceAll(str, search, replacement) { return str.split(search).join(replacement); } const str = "Hello world!"; const replacedStr = replaceAll(str, "o", "x"); console.log(replacedStr);
Output:
Hellx wxrld!