JavaScript String match() 方法
示例
使用字符串搜索“ain”
let text = "The rain in SPAIN stays mainly in the plain";
text.match("ain");
自己动手试一试 »
使用正则表达式搜索“ain”
let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/);
自己动手试一试 »
全局搜索“ain”
let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/g);
自己动手试一试 »
全局、不区分大小写的搜索
let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/gi);
自己动手试一试 »
描述
match()
方法将字符串与正则表达式进行匹配**
match()
方法返回一个包含匹配项的数组。
如果没有找到匹配项,match()
方法返回 null。
语法
string.match(match)
参数
参数 | 描述 |
match | 必需。 搜索值。 正则表达式(或将转换为正则表达式的字符串)。 |
返回值
类型 | 描述 |
一个数组 或 null | 包含匹配项的数组。 如果没有找到匹配项,则为 null 。 |
区别
String match() 和 String search()
match()
方法返回一个匹配项数组。
search()
方法返回第一个匹配项的位置。
正则表达式搜索方法
在 JavaScript 中,可以使用不同的方法进行正则表达式文本搜索。
以模式作为正则表达式,这些是最常用的方法
示例 | 描述 |
---|---|
text.match(pattern) | 字符串方法 match() |
text.search(pattern) | 字符串方法 search() |
pattern.exec(text) | RegExp 方法 exec() |
pattern.test(text) | RegExp 方法 test() |
浏览器支持
match()
是 ECMAScript1 (ES1) 的特性。
ES1 (JavaScript 1997) 在所有浏览器中都得到完全支持
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 是 |