DIV CSS 佈局教程網

JavaScript 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!

三個關鍵行為

一、默認區分大小寫。這就是 "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()。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved