JavaScript - Symbol.matchAll 属性
ES6 中添加的一个常用 JavaScript 符号是 Symbol.matchAll 属性。它充当符号对象的键。
Symbol.matchAll 属性用于创建一个表示正则表达式匹配的对象,可以迭代该对象以检索字符串中的所有匹配项。当使用全局正则表达式(该表达式会匹配字符串中某个模式的多个实例)时,此属性非常有用。
语法
以下是 JavaScript Symbol.matchAll 属性的语法 -
regExp[Symbol.matchAll](str);
参数
此属性接受一个字符串,用于查找正则表达式的匹配项。
返回值
此属性返回一个迭代器,该迭代器返回正则表达式匹配项。
示例
示例 1
让我们看下面的示例,我们将使用 for of 循环来迭代匹配项。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = 'Tutorials, Point';
const reg_exp = /([A-Z])\w+/g;
for (const match of x.matchAll(reg_exp)) {
document.write(match[1] + " < br > ");
}
</script>
</body>
</html>
如果我们执行上述程序,它将在网页上显示文本。
示例 2
考虑另一种场景,我们将使用 Array.from 将迭代器转换为数组。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = 'HELLO , everyone';
const reg_exp = /[A-Z]/g;
const a = Array.from(x.matchAll(reg_exp), m => m[0]);
document.write(JSON.stringify(a));
</script>
</body>
</html>
执行上述脚本后,网页上将显示一段文本。
示例 3
在下面的示例中,我们将使用标志并返回一个包含所有匹配子字符串的迭代器,不区分大小写。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const str = 'TutorialsPoint, TP';
const regex = /tp/gi;
const matches = str.matchAll(regex);
for (const match of matches) {
document.write(match[0]);
}
</script>
</body>
</html>
当我们执行脚本时,它将在网页上显示一段文本。

