Let’s try some examples:
- Here is the first example to initialize a text in a variable, then replace it with another text.
- What happens if a given string is found multiple times. In that case, the
replace()function will replace the first occurrence of the given string.
Execute the above code and see the results:
The result clearly shows that the first occurrence is replaced with a new string, but the second occurrence is not replaced. So, how can I replace all the occurrences of a given string? Let’s check the next example:
- We can also define the regular expression and the function will replace all occurrences matching that regular expression.
See the below example, where we defined a regular expression to replace string globally.
Run the above example and see the results.
- Basically, the regular expression is used to match patterns. To replace all occurrences of any string, we can use
Run the above code and see the results.