正则表达式 (Regex) 看起来很神秘,但功能非常强大。它们允许你匹配文本中的复杂模式。
测试模式
javascript
const hasNumber = /d+/;
console.log(hasNumber.test("Hello 123")); // true
console.log(hasNumber.test("Hello World")); // false提取数据 (捕获组)
现代 JS 允许"命名捕获组",这使得 Regex 更易读。
javascript
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"