DIV CSS 佈局教程網

match 方法:搜尋字串並回傳比對結果
編輯:關於JavaScript     

String.prototype.match 用於在字串中搜尋指定內容,找到就回傳比對結果,找不到則回傳 null。字串參數形式的比對是區分大小寫的。

<!DOCTYPE html>
<html>
<body>
<script>
var str = "Hello world!";
document.write(str.match("world")  + "<br>");  // world
document.write(str.match("World")  + "<br>");  // null(大小寫不符)
document.write(str.match("worlld") + "<br>");  // null(拼字錯誤)
document.write(str.match("world!"));             // world!
</script>
</body>
</html>

輸出:

world
null
null
world!

回傳值的型態會隨參數而變

這是 match 最容易讓人困惑的地方:

1. 傳入字串時,行為等同於只搜尋一次的無 g 旗標正則,回傳值是「比對結果陣列」或 null。陣列第 0 項是比對到的完整字串,另外還帶有 index(位置)與 input(原字串)等屬性。

2. 傳入帶 g 旗標的正則時,回傳值是「所有比對結果組成的陣列」,且不含捕獲群組,也沒有 index 屬性。

var s = "a1 b22 c333";

s.match(/\d+/);    // ["1"], 帶 index: 1 等屬性
s.match(/\d+/g);   // ["1", "22", "333"],只有結果,沒有位置資訊
s.match(/(\d)(\d)/); // ["22", "2", "2"],第 1、2 項是捕獲群組

該用哪個方法

如果只是要判斷存不存在,用 str.includes("world") 或 /world/.test(str) 更直觀。

如果要取代內容,該用 replace 而不是 match。

如果需要所有比對位置與群組,ES2020 之後建議用 str.matchAll(regexp) 搭配 for...of 走訪,它能同時給你位置與捕獲群組,補上了 match + /g 的不足。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved