How can I replace all occurrences of a string in JavaScript?
Rashid D
rashid d profile pic

To replace all occurrences of a string in JavaScript, you can use thereplace() method in combination with regular expressions. Here's a step-by-step guide on how to achieve this: 1. Create a regular expression with the global flag (g) to match all occurrences of the string:

1
2
3
4

   const searchStr = 'old';
   const regex = new RegExp(searchStr, 'g');
   

2. Use thereplace() method on the target string and pass the regular expression and the replacement string as arguments:

1
2
3
4
5
6

   const targetStr = 'old old old';
   const replacementStr = 'new';

   const result = targetStr.replace(regex, replacementStr);
   

3. Thereplace() method returns a new string with all occurrences of the search string replaced. Assign the result to a variable (result in the example) to capture the modified string. In the given example, thereplace() method will replace all occurrences of'old' with'new' in thetargetStr string. The resulting value will be'new new new'. Note: If the search string contains any characters with special meaning in regular expressions (e.g.,$,^,*), make sure to escape them usingRegExp.escape() or by adding backslashes before them in the search string. If you need to perform case-insensitive replacements, you can add thei flag to the regular expression, like this:

1
2

const regex = new RegExp(searchStr, 'gi');

In this case, both uppercase and lowercase occurrences of the search string will be replaced. By using thereplace() method with a regular expression and the global flag, you can easily replace all occurrences of a string in JavaScript.