This commit is contained in:
Ilya Kantor 2020-12-13 21:17:05 +03:00
parent 8bc2e921eb
commit c275ba48b6

View file

@ -228,6 +228,23 @@ alert(result); // Smith, John
Using a function gives us the ultimate replacement power, because it gets all the information about the match, has access to outer variables and can do everything.
## str.replaceAll(str|regexp, str|func)
This method is essentially the same as `str.replace`, with two major differences:
1. If the first argument is a string, it replaces *all occurences* of the string, while `replace` replaces only the *first occurence*.
2. If the first argument is a regular expression without the `g` flag, there'll be an error. With `g` flag, it works the same as `replace`.
The main use case for `replaceAll` is replacing all occurences of a string.
Like this:
```js run
// replace all dashes by a colon
alert('12-34-56'.replaceAll("-", ":")) // 12:34:56
```
## regexp.exec(str)
The method `regexp.exec(str)` method returns a match for `regexp` in the string `str`. Unlike previous methods, it's called on a regexp, not on a string.