DIV CSS 佈局教程網

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

字串的 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!

回傳值到底是什麼

這是最容易被誤解的地方。傳入字串時,回傳的是一個陣列:

"Hello world!".match("world");
// ["world"]   只有一個元素:整體比對結果

傳入含捕獲群組的正則時,陣列會多出額外元素:

"2026-08-26".match(/(\d+)-(\d+)-(\d+)/);
// ["2026-08-26", "2026", "08", "26"]
//   [0] 整體比對  [1]~[3] 各個群組

實用技巧

str.match(/i/gi);              // 不分大小寫,列出所有符合
str.match(/hello/i);           // 不分大小寫
str.includes("world");         // 只想知道有沒有?用 includes 更清楚

選擇建議:只需要判斷存在與否,用 includes();需要取出符合的內容,用 match();需要替換,用 replace();需要位置資訊(index)或分組名稱,則用 matchAll() 搭配 /g 旗標。

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