js: Use regular naming to capture the year, month, and day in the extracted date

Requirement: Extract the year, month, and day of the date

Method 1: Use a capture group

let text = "2023-06-01"

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

output result

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

Method 1: Use named capture groups

let text = "2023-06-01"

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

output result

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

reference

Guess you like

Origin blog.csdn.net/mouday/article/details/130987855