replace() 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 the
replace() 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);
replace() 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, the
replace() method will replace all occurrences of
'new' in the
targetStr 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 using
RegExp.escape() or by adding backslashes before them in the search string.
If you need to perform case-insensitive replacements, you can add the
i flag to the regular expression, like this:
const regex = new RegExp(searchStr, 'gi');
In this case, both uppercase and lowercase occurrences of the search string will be replaced.
By using the