Let’s try some examples:
- Here is the first example to initialize a text in a variable, then replace it with another text.1234let str = "Hello World!"let result = str.replace("World", "TecAdmin")console.log(result)
- 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.12345let str = "Mr Bean has a green Apple and a Red Apple"let result = str.replace("Apple", "Strawberries")console.log(result)
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.123456let str = "Mr Bean has a green Apple and a red Apple"const regex = "/Apple/ig"let result = str.replace("Apple", "Strawberries")console.log(result)
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.