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!
一、默認區分大小寫。這就是 "World" 匹配失敗的原因。需要忽略大小寫時傳入正則:
str.match(/world/i); // ["world"]
二、返回值形態取決於是否使用 g 標誌。
"a1b2c3".match(/\d/); // ["1", index: 1, input: "a1b2c3", groups: undefined]
"a1b2c3".match(/\d/g); // ["1", "2", "3"],只返回匹配數組,丟失位置等信息
加 g 之後返回所有匹配組成的數組,但不再包含 index、input 等附加屬性;不加 g 則只返回第一個匹配及完整信息。這個差異需要根據需求選擇。
三、沒匹配到返回 null 而非空數組。因此使用前要判空,直接對返回值取 [0] 會拋出錯誤:
var m = str.match(/xyz/);
if (m) { console.log(m[0]); }
includes() 或 test(),語義更清晰。match(),或更靈活的 matchAll()。replace()。