match
是 JavaScript 中的一个字符串方法,用于检索字符串中是否含有指定的正则表达式匹配项,并返回一个数组,其中包含了整个匹配结果以及任何括号捕获的子匹配。如果没有找到匹配项,则返回 null
。
/abc/
匹配字符串中的 "abc"。g
标志,如 /abc/g
匹配字符串中所有出现的 "abc"。i
标志,如 /abc/i
匹配 "abc", "ABC", "aBc" 等。m
标志,允许 ^
和 $
分别匹配每一行的开始和结束。// 基本匹配
let str = "Hello, world!";
let result = str.match(/world/);
console.log(result); // 输出: ["world", index: 7, input: "Hello, world!", groups: undefined]
// 全局匹配
str = "apple banana apple";
result = str.match(/apple/g);
console.log(result); // 输出: ["apple", "apple"]
// 不区分大小写匹配
str = "Apple is red.";
result = str.match(/apple/i);
console.log(result); // 输出: ["Apple", index: 0, input: "Apple is red.", groups: undefined]
// 使用括号捕获子匹配
str = "Date: 2023-04-30";
result = str.match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(result);
// 输出: ["2023-04-30", "2023", "04", "30", index: 6, input: "Date: 2023-04-30", groups: undefined]
问题:match
方法返回 null
,即使看起来应该有匹配项。
原因:
g
当需要匹配多个实例时。解决方法:
g
标志,添加该标志并处理返回的数组。通过理解这些基础概念和应用场景,你可以更有效地使用 match
方法来解决实际问题。
领取专属 10元无门槛券
手把手带您无忧上云