How to Replace All Occurrences of a String in JavaScript?
Last Updated : 19 Nov, 2024
Here are different approaches to replace all occurrences of a string in JavaScript.
1. Using string.replace() Method
The string.replace() method is used to replace a part of the given string with another string or a regular expression. The original string will remain unchanged.
Syntax
str.replace(replacing_string, Original_string);
JavaScript // Origin String const str = 'Welcome GeeksforGeeks, Welcome geeks'; // Replace all occurrence of Welcome with Hello const newString = str.replace(/Welcome/gi, 'Hello'); // Display the result console.log(newString);
OutputHello GeeksforGeeks, Hello geeks
2. Using String split() and join() Methods
We can split the strings of text with the split() method and join strings using the replace characters with the join() method.
JavaScript // Original String const str = 'Welcome GeeksforGeeks, Welcome geeks'; // Replace all occurrence of Welcome with Hello const newString = str.split('Welcome').join('Hello'); // Display the result console.log(newString);
OutputHello GeeksforGeeks, Hello geeks
3. Using replaceAll() Method
The replaceAll() method is used to replace all the matches of a string with a specified string or a regular expression. The original string is left unchanged after this operation.
JavaScript // Original String const str = 'Welcome GeeksforGeeks, Welcome geeks'; // Replace all occurrences of Welcome with Hello const newString = str.replaceAll("Welcome", "Hello"); // Display the result console.log(newString);
OutputHello GeeksforGeeks, Hello geeks
4. Using Regular Expression
To replace all occurrences of a string in JavaScript using a regular expression, we can use the regular expression with the global (g
) Flag.
JavaScript const str = 'Welcome GeeksforGeeks, Welcome geeks'; const searchString ="Welcome"; const replacementString ="Hello"; let regex = new RegExp(searchString, 'g'); let replacedString = str.replace(regex, replacementString); console.log(replacedString);
OutputHello GeeksforGeeks, Hello geeks
5. Using reduce() Method
We can split the string into an array of substrings using the split() method, and then we use the reduce() method to concatenate the substrings, inserting the replacement string where the original substring occurs. This method gives us fine control over the replacement process and can be useful for more complex string manipulations.
JavaScript // Original String const str = 'Welcome GeeksforGeeks, Welcome geeks'; const searchString = "Welcome"; const replacementString = "Hello"; // Replace all occurrences of Welcome with Hello const newString = str.split(searchString).reduce((acc, current, index, array) => { return acc + current + (index < array.length - 1 ? replacementString : ''); }, ''); // Display the result console.log(newString);
OutputHello GeeksforGeeks, Hello geeks