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 |
是 | 是 | 是 | 是 | 是 | 是 |