How to use String split() and join() Method In Javascript
We can split the strings of text with the JavaScript split method and join strings using the replace characters with the join method.
Example: In this example we replaces all occurrences of ‘Welcome’ with ‘Hello’ in the string str by splitting and joining.
// Original String
const str = 'Welcome w3wiki, Welcome geeks';
// Replace all occurrence of Welcome with Hello
const newString = str.split('Welcome').join('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