How to use string.replace() method In Javascript
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.
Example: In this example we replaces all occurrences of ‘Welcome’ with ‘Hello’ in the string str, using a case-insensitive global regex
// Origin String
const str = 'Welcome w3wiki, Welcome geeks';
// Replace all occurrence of Welcome with Hello
const newString = str.replace(/Welcome/gi, '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