replaceAll | Javascript

 

const str = 'this is a JSsnippets example';

const updatedStr = str.replace('example', 'snippet'); // 'this is a  JSsnippets snippet'


The tricky part is that replace method replaces only the very first match of the substring we have passed:


const str = 'this is a JSsnippets example and examples are great';

const updatedStr = str.replace('example', 'snippet'); //'this is a JSsnippets snippet and examples are great'

In order to go through this, we need to use a global regexp instead:


const str = 'this is a JSsnippets example and examples are great';

const updatedStr = str.replace(/example/g, 'snippet'); //'this is a JSsnippets snippet and snippets are greatr'

but now we have new friend in town, replaceAll

const str = 'this is a JSsnippets example and examples are great';

const updatedStr = str.replaceAll('example', 'snippet'); //'this is a JSsnippets snippet and snippets are greatr'
 

AI Explanation

In this JavaScript code snippet, we are using the `replace()` method to replace a substring in a string with another substring. 1. The first example: ```javascript const str = 'this is a JSsnippets example'; const updatedStr = str.replace('example', 'snippet'); // 'this is a JSsnippets snippet' ``` In this example, we are replacing the first occurrence of the string 'example' in the `str` variable with 'snippet'. 2. The second example: ```javascript const str = 'this is a JSsnippets example and examples are great'; const updatedStr = str.replace('example', 'snippet'); //'this is a JSsnippets snippet and examples are great' ``` In this example, the same logic applies, but this time we have multiple occurrences of 'example' in the `str` variable. The `replace()` method only replaces the first occurrence. 3. To replace all occurrences: To replace all occurrences of a substring in a string, we need to use a global regular expression (`/example/g`) in the `replace()` method: ```javascript const updatedStr = str.replace(/example/g, 'snippet'); //'this is a JSsnippets snippet and snippets are greatr' ``` 4. Using the `replaceAll()` method (ES2021): In ES2021, a new `replaceAll()` method has been introduced to replace all occurrences of a substring in a string: ```javascript const updatedStr = str.replaceAll('example', 'snippet'); //'this is a JSsnippets snippet and snippets are greatr' ``` This method simplifies the process of replacing all occurrences without the need for regular expressions. In summary, the `replace()` method only replaces the first occurrence of a substring in a string, while using a global regular expression or `replaceAll()` method allows us to replace all occurrences.