JavaScript String matchAll() 方法



JavaScript String matchAll() 方法检索当前字符串中与指定正则表达式 (regex) 匹配的所有结果的迭代器。但是,如果指定的正则表达式在当前字符串中找不到任何匹配项,则它将返回一个空迭代器。

如果正则表达式不包含“g”标志或未设置全局 (g) 标志,则会抛出“TypeError”异常。

语法

以下是 JavaScript String matchAll() 方法的语法:

matchAll(regexp)

参数

此方法接受一个名为“regexp”的参数,如下所述:

  • regexp - 它是一个正则表达式对象。

返回值

此方法返回当前字符串中匹配项的迭代器,如果未找到任何匹配项,则返回空迭代器。

示例 1

如果指定的正则表达式匹配此字符串,它将返回一个包含此字符串中所有匹配结果的迭代器。

在以下程序中,我们使用 JavaScript String matchAll() 方法检索与该字符串“TutorialsPointTuto”匹配的所有结果的迭代器,并针对指定的正则表达式/Tuto/g

<html>
<head>
<title>JavaScript String matchAll() Method</title>
</head>
<body>
<script>
   const str = "TutorialsPointTuto";
   document.write("String: ", str);
   const regex =/Tuto/g;
   document.write("<br>Regular expression: ", regex);
   //using the matchAll() function
   const iterator_array = [...str.matchAll(regex)];
   try {
      document.write("<br>An iterator: ", iterator_array);
   } catch (error) {
      document.write("<br>", error);
   } 
</script>
</body>
</html>

输出

以上程序返回一个迭代器,如下所示:

String: TutorialsPointTuto
Regular expression: /Tuto/g
An iterator: Tuto,Tuto

示例 2

如果指定的正则表达式匹配此字符串,它将返回一个迭代器。

以下是 JavaScript String matchAll() 方法的另一个示例。我们使用此方法检索与该字符串“JavaScript”匹配的所有结果的迭代器,并针对指定的正则表达式/java/[A-Z]*/g

<html>
<head>
<title>JavaScript String matchAll() Method</title>
</head>
<body>
<script>
   const str = "JavaScript";
   document.write("String: ", str);
   const regex = /java[A-Z]*/g;
   document.write("<br>Regular expression: ", regex);
   //using the matchAll() function
   const iterator_array = [...str.matchAll(regex)];
   try {
      document.write("<br>An iterator: ", iterator_array);
   } catch (error) {
      document.write("<br>", error);
   }
</script>
</body>
</html>

输出

执行上述程序后,它将返回一个空迭代器,如下所示:

String: JavaScript
Regular expression: /java[A-Z]*/g
An iterator:

示例 3

如果正则表达式 (regexp) 未设置全局 (g) 标志或不包含“g”,则会抛出'TypeError'异常。

在以下示例中,我们使用 JavaScript String matchAll() 方法检索与该字符串“Hyper Text Markup Language”匹配的所有结果的迭代器,并针对指定的正则表达式/Lan[a-z]*/。由于正则表达式不包含全局("g"),因此它将抛出“TypeError”异常。

<html>
<head>
<title>JavaScript String matchAll() Method</title>
</head>
<body>
<script>
   const str = "Hyper Text Markup Language";
   document.write("String: ", str);
   const regex = /Lan[a-z]*/;
   document.write("<br>Regular expression: ", regex);
   //using the matchAll() function
   try {
      document.write("An iterators: ", str.matchAll(regex));
   } catch (error) {
      document.write("<br>", error);
   }
</script>
</body>
</html>

输出

上述程序抛出'TypeError'异常。

String: Hyper Text Markup Language
Regular expression: /Lan[a-z]*/
TypeError: String.prototype.matchAll called with a non-global RegExp argument
广告

© . All rights reserved.