// 使用RegExp需要注意转义符
let re = new RegExp('(?\\d{4})-(?\\d{2})-(?\\d{2})');
let match = re.exec('2021-12-14');
console.log(match); // 没有匹配到会返回null
if(match){
let {year, month, day} = match.groups;
console.log(year, month, day);
// 2021 12 14
}
匹配结果的内容
[
'2021-12-14',
'2021',
'12',
'14',
index: 0,
input: '2021-12-14',
groups: { year: '2021', month: '12', day: '14' }
]
参考 JavaScript 正则命名分组【推荐】