js:使用正则命名捕获分组提取日期中的年月日

需求:提取日期中的年月日

方法一:使用捕获组

let text = "2023-06-01"

let result = text.match(/(\d+)-(\d+)-(\d+)/)
console.log(result);

输出结果

[
    '2023-06-01',
    '2023',
    '06',
    '01',
    index: 0,
    input: '2023-06-01',
    groups: undefined
  ]

方法一:使用命名捕获组

let text = "2023-06-01"

let result = text.match(/(?<year>\d+)-(?<month>\d+)-(?<day>\d+)/)
console.log(result.groups);

输出结果

{
    
     year: '2023', month: '06', day: '01' }

参考

猜你喜欢

转载自blog.csdn.net/mouday/article/details/130987855
今日推荐