How to use replaceAll() Method In Javascript
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.
Example: In this example we replaces all occurrences of ‘Welcome’ with ‘Hello’ in the string str using the replaceAll() method, then logs the result.
// Original String
const str = 'Welcome w3wiki, Welcome geeks';
// Replace all occurrences of Welcome with Hello
const newString = str.replaceAll("Welcome", "Hello");
// Display the result
console.log(newString);
Output
Hello w3wiki, Hello geeks
How to replace all occurrences of a string in JavaScript ?
Replacing all occurrences of a string in JavaScript is a common task in text processing. It involves identifying and substituting specific substrings within a larger string. This capability is crucial for tasks such as data cleaning, formatting, and transforming text in various applications.
These are the following methods to replace all occurrences of a string in JavaScript:
Table of Content
- Using string.replace() method
- Using String split() and join() Method
- Using replaceAll() Method
- Using regular expression
- Using reduce() Function