JavaScript matchAll正则匹配

JavaScript matchAll正则匹配教程

JavaScript 中,matchAll() 方法返回对 字符串 使用 正则表达式 的所有匹配项。

JavaScript matchAll()函数详解

定义

matchAll() 方法返回对字符串使用正则表达式的所有匹配项。

语法

regexp[Symbol.matchAll](str);

参数

参数 描述
str 一个 String 的匹配对象。

返回值

一个迭代器。

案例

matchAll函数匹配查找字符串

使用 matchAll 函数,在一个字符串中查找匹配另一个字符串

<!DOCTYPE html> <html> <head> <title>JavaScript matchAll查找字符串</title> <script type="text/javascript"> console.log("嗨客网(www.haicoder.net)"); var re = /[0-9]+/g; var str = '2022-02-16'; var result = re[Symbol.matchAll](str); console.log("Array =", Array.from(result, x => x[0])); </script> </head> </html>

程序运行后,控制台输出如下:

04_javascript matchAll方法正则表达式.png

首先,我们使用字面量的方式,创建了一个正则表达式 对象,接着,我们定义了一个字符串 变量 str,最后,我们使用 matchAll 方法在字符串中进行匹配。

JavaScript matchAll正则匹配总结

在 JavaScript 中,matchAll() 方法返回对字符串使用正则表达式的所有匹配项。