diff options
| author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
|---|---|---|
| committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
| commit | 074785cea106179cb3305637055ab0a009ca74f2 (patch) | |
| tree | e6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/ru/web/javascript/reference/global_objects/string/matchall/index.html | |
| parent | da78a9e329e272dedb2400b79a3bdeebff387d47 (diff) | |
| download | translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2 translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip | |
initial commit
Diffstat (limited to 'files/ru/web/javascript/reference/global_objects/string/matchall/index.html')
| -rw-r--r-- | files/ru/web/javascript/reference/global_objects/string/matchall/index.html | 120 |
1 files changed, 120 insertions, 0 deletions
diff --git a/files/ru/web/javascript/reference/global_objects/string/matchall/index.html b/files/ru/web/javascript/reference/global_objects/string/matchall/index.html new file mode 100644 index 0000000000..6c8defbc17 --- /dev/null +++ b/files/ru/web/javascript/reference/global_objects/string/matchall/index.html @@ -0,0 +1,120 @@ +--- +title: String.prototype.matchAll() +slug: Web/JavaScript/Reference/Global_Objects/String/matchAll +tags: + - JavaScript + - Method + - Prototype + - Reference + - Regular Expressions + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/matchAll +--- +<div>{{JSRef}}</div> + +<p>Метод <strong><code>matchAll()</code></strong> возвращает итератор по всем результатам при сопоставлении <em>строки с регулярным выражением</em>.</p> + +<div>{{EmbedInteractiveExample("pages/js/string-matchall.html")}}</div> + + + +<h2 id="Синтаксис">Синтаксис</h2> + +<pre class="syntaxbox notranslate"><var>str</var>.matchAll(<var>regexp</var>)</pre> + +<h3 id="Параметры">Параметры</h3> + +<dl> + <dt><code>regexp</code></dt> + <dd>Объект регулярного выражения. Если передано значение, не являющееся объектом регулярного выражения, оно неявно преобразуется в {{jsxref("RegExp")}} используя <code>new RegExp(obj)</code>.</dd> +</dl> + +<h3 id="Возвращаемое_значение">Возвращаемое значение</h3> + +<p>Возвращается <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">iterator</a> (не перезапускаемый).</p> + +<h2 id="Примеры">Примеры</h2> + +<h3 id="Regexp.exec_и_matchAll">Regexp.exec() и matchAll()</h3> + +<p>До добавления метода <code>matchAll</code> в JavaScript, можно было использовать метод <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec">regexp.exec</a> (и регулярные выражения с флагом <code>/g</code> ) в цикле для получения доступа к совпадениям:</p> + +<pre class="brush: js notranslate">const regexp = RegExp('foo*','g'); +const str = 'table football, foosball'; + +while ((matches = regexp.exec(str)) !== null) { + console.log(`Found ${matches[0]}. Next starts at ${regexp.lastIndex}.`); + // expected output: "Found foo. Next starts at 9." + // expected output: "Found foo. Next starts at 19." +} +</pre> + +<p>С появлением <code>matchAll</code>, нет необходимости использовать цикл <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/while">while</a></code> и метод <code>exec</code> с флагом <code>/g</code>.<br> + Используя вместо этого метод <code>matchAll</code>, вы получаете итератор, который вы можете использовать более удобно с конструкциями <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code>, <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">array spread</a>, или {{jsxref("Array.from()")}} :</p> + +<pre class="brush: js notranslate">const regexp = RegExp('foo*','g'); +const str = 'table football, foosball'; +let matches = str.matchAll(regexp); + +for (const match of matches) { + console.log(match); +} +// Array [ "foo" ] +// Array [ "foo" ] + +// итерация больше недоступна после вызова for of +// Для создания нового итератора вызовите matchAll повторно +matches = str.matchAll(regexp); + +Array.from(matches, m => m[0]); +// Array [ "foo", "foo" ] +</pre> + +<h3 id="Улучшенный_доступ_к_группам_захвата">Улучшенный доступ к группам захвата</h3> + +<p>Еще одна веская причина использовать <code>matchAll</code> это улучшенный доступ к группам захвата. Группы захвата игнорируются при использовании <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match">match()</a></code> с глобальным флагом <code>/g</code>:</p> + +<pre class="brush: js notranslate">var regexp = /t(e)(st(\d?))/g; +var str = 'test1test2'; + +str.match(regexp); +// Array ['test1', 'test2']</pre> + +<p>С <code>matchAll</code> у вас появляется к ним доступ:</p> + +<pre class="brush: js notranslate">let array = [...str.matchAll(regexp)]; + +array[0]; +// ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4] +array[1]; +// ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4] +</pre> + +<h2 id="Спецификации">Спецификации</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Спецификация</th> + <th scope="col">Статус</th> + </tr> + <tr> + <td><a href="https://tc39.github.io/proposal-string-matchall/#sec-string-prototype-matchall">String.prototype.matchAll</a></td> + <td>Stage 3</td> + </tr> + </tbody> +</table> + +<h2 id="Браузерная_совместимость">Браузерная совместимость</h2> + +<p class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.String.matchAll")}}</p> + +<h2 id="Смотрите_также">Смотрите также</h2> + +<ul> + <li>{{jsxref("RegExp")}}</li> + <li>{{jsxref("RegExp.prototype.exec()")}}</li> + <li>{{jsxref("RegExp.prototype.test()")}}</li> +</ul> |
