aboutsummaryrefslogtreecommitdiff
path: root/files/uk/web/javascript/reference/global_objects/string/matchall
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:43:23 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:43:23 -0500
commit218934fa2ed1c702a6d3923d2aa2cc6b43c48684 (patch)
treea9ef8ac1e1b8fe4207b6d64d3841bfb8990b6fd0 /files/uk/web/javascript/reference/global_objects/string/matchall
parent074785cea106179cb3305637055ab0a009ca74f2 (diff)
downloadtranslated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.gz
translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.bz2
translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.zip
initial commit
Diffstat (limited to 'files/uk/web/javascript/reference/global_objects/string/matchall')
-rw-r--r--files/uk/web/javascript/reference/global_objects/string/matchall/index.html143
1 files changed, 143 insertions, 0 deletions
diff --git a/files/uk/web/javascript/reference/global_objects/string/matchall/index.html b/files/uk/web/javascript/reference/global_objects/string/matchall/index.html
new file mode 100644
index 0000000000..396fb3b2bc
--- /dev/null
+++ b/files/uk/web/javascript/reference/global_objects/string/matchall/index.html
@@ -0,0 +1,143 @@
+---
+title: String.prototype.matchAll()
+slug: Web/JavaScript/Reference/Global_Objects/String/matchAll
+tags:
+ - JavaScript
+ - String
+ - Регулярні Вирази
+ - метод
+translation_of: Web/JavaScript/Reference/Global_Objects/String/matchAll
+---
+<div>{{JSRef}}</div>
+
+<p>Метод <strong><code>matchAll()</code></strong> повертає ітератор з усіма збігами <em>рядка</em> з <em><a href="/uk/docs/Web/JavaScript/Guide/Regular_Expressions">регулярним виразом</a></em>, а також <a href="/uk/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges">захоплені групи</a>.</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><var>regexp</var></code></dt>
+ <dd>
+ <p>Об'єкт регулярного виразу.</p>
+
+ <p>Якщо передано об'єкт <code>obj</code>, який не є регулярним виразом, він неявно перетворюється на {{jsxref("RegExp")}} за допомогою <code>new RegExp(<var>obj</var>)</code>.</p>
+
+ <p>Об'єкт <code>RegExp</code> повинен мати прапор <code>/g</code>, інакше буде викинуто помилку <code>TypeError</code>.</p>
+ </dd>
+</dl>
+
+<h3 id="Значення_що_повертається">Значення, що повертається</h3>
+
+<p><a href="/uk/docs/Web/JavaScript/Guide/Iterators_and_Generators">Ітератор</a> (ітерабельний об'єкт, який не можна повторно запустити).</p>
+
+<h2 id="Приклади">Приклади</h2>
+
+<h3 id="Regexp.exec_та_matchAll">Regexp.exec() та matchAll()</h3>
+
+<p>До появи у JavaScript методу <code>matchAll</code> можна було використовувати виклики <a href="/uk/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec">regexp.exec</a> (а також регулярні вирази з прапором <code>/g</code>) у циклі, щоб отримати усі збіги:</p>
+
+<pre class="brush: js notranslate">const regexp = RegExp('фу[а-я]*','g');
+const str = 'настільний футбол, фусбол';
+let match;
+
+while ((match = regexp.exec(str)) !== null) {
+ console.log(`Знайдено ${match[0]} початок=${match.index} кінець=${regexp.lastIndex}.`);
+ // виведе: "Знайдено футбол початок=11 кінець=17."
+ // виведе: "Знайдено фусбол початок=19 кінець=25."
+}</pre>
+
+<p>З методом <code>matchAll</code> можна уникнути використання циклу {{jsxref("Statements/while", "while")}} та методу <code>exec</code> з <code>g</code>.</p>
+
+<p>Замість цього, використовуючи <code>matchAll</code>, ви отримуєте ітератор, який можна використовувати з більш зручними конструкціями {{jsxref("Statements/for...of", "for...of")}}, {{jsxref("Operators/Spread_syntax", "розкладанням масиву")}} чи {{jsxref("Array.from()")}}:</p>
+
+<pre class="brush: js notranslate">const regexp = RegExp('фу[а-я]*','g');
+const str = 'настільний футбол, фусбол';
+const matches = str.matchAll(regexp);
+
+for (const match of matches) {
+ console.log(`Знайдено ${match[0]} початок=${match.index} кінець=${match.index + match[0].length}.`);
+}
+// виведе: "Знайдено футбол початок=11 кінцець=17."
+// виведе: "Знайдень фусбол початок=19 кінець=25."
+
+// Ітератор matches є вичерпаним після перебору for..of
+// Викличте matchAll ще раз, щоб створити новий ітератор
+Array.from(str.matchAll(regexp), m =&gt; m[0]);
+// Array [ "футбол", "фусбол" ]</pre>
+
+<p>Метод <code>matchAll</code> викине виняток, якщо прапор <code>g</code> відсутній.</p>
+
+<pre class="brush: js notranslate">const regexp = RegExp('[а-в]','');
+const str = 'абв';
+str.matchAll(regexp);
+// TypeError
+</pre>
+
+<p><code>matchAll</code> робить внутрішній клон <code><var>regexp</var></code><var>,</var> тому, на відміну від {{jsxref("Global_Objects/RegExp/exec", "regexp.exec()")}}, <code>lastIndex</code> не змінюється під час пошуку.</p>
+
+<pre class="brush: js notranslate">const regexp = RegExp('[а-в]','g');
+regexp.lastIndex = 1;
+const str = 'абв';
+Array.from(str.matchAll(regexp), m =&gt; `${regexp.lastIndex} ${m[0]}`);
+// Array [ "1 б", "1 в" ]</pre>
+
+<h3 id="Кращий_доступ_до_захоплених_груп_ніж_у_String.prototype.match">Кращий доступ до захоплених груп (ніж у String.prototype.match())</h3>
+
+<p>Ще одна приваблива причина використовувати <code>matchAll</code> - покращений доступ до захоплених груп.</p>
+
+<p>Захоплені групи ігноруються при використанні {{jsxref("Global_Objects/String/match", "match()")}} з глобальним прапором <code>/g</code>:</p>
+
+<pre class="brush: js notranslate">let regexp = /т(е)(ст(\d?))/g;
+let str = 'тест1тест2';
+
+str.match(regexp);
+// Array ['тест1', 'тест2']</pre>
+
+<p>Використовуючи <code>matchAll</code>, ви можете легко звертатись до захоплених груп:</p>
+
+<pre class="brush: js notranslate">let array = [...str.matchAll(regexp)];
+
+array[0];
+// ['тест1', 'е', 'ст1', '1', index: 0, input: 'тест1тест2', length: 4]
+array[1];
+// ['тест2', 'е', 'ст2', '2', index: 5, input: 'тест1тест2', length: 4]
+</pre>
+
+<h2 id="Специфікації">Специфікації</h2>
+
+<table class="standard-table">
+ <thead>
+ <tr>
+ <th scope="col">Специфікація</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>{{SpecName('ESDraft', '#sec-string.prototype.matchall', 'String.prototype.matchAll')}}</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("String.prototype.match()")}}</li>
+ <li><a href="/uk/docs/Web/JavaScript/Guide/Regular_Expressions">Використання регулярних виразів у JavaScript</a></li>
+ <li><a href="/uk/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges">Захоплені групи</a></li>
+ <li>{{jsxref("RegExp")}}</li>
+ <li>{{jsxref("RegExp.prototype.exec()")}}</li>
+ <li>{{jsxref("RegExp.prototype.test()")}}</li>
+</ul>