函数与逻辑2026年1月20日星期二

正则表达式

模式匹配和文本验证。

广告

查看赞助商以支持 JS Fruggal。

正则表达式 (Regex) 看起来很神秘,但功能非常强大。它们允许你匹配文本中的复杂模式。

测试模式

const hasNumber = /d+/;
console.log(hasNumber.test("Hello 123")); // true
console.log(hasNumber.test("Hello World")); // false

提取数据 (捕获组)

现代 JS 允许"命名捕获组",这使得 Regex 更易读。

const dateStr = "2026-01-30";
const pattern = /(?<year>d{4})-(?<month>d{2})-(?<day>d{2})/;

const match = pattern.exec(dateStr);
console.log(match.groups.year);  // "2026"
console.log(match.groups.month); // "01"
广告

查看赞助商以支持 JS Fruggal。