Home » Javascript » Can't understand regular expression in Javascript when match dates

Can't understand regular expression in Javascript when match dates

Posted by: admin February 23, 2020 Leave a comment

Questions:

so.. this is a part of an answer code to detect Hours and mintues in a given time

function scheduleMeeting(startTime,durationMinutes) { 
    var [ , meetingStartHour, meetingStartMinutes ] = startTime.match(/^(\d{1,2}):(\d{2})$/) || [];
...
}

What is this (/^(\d{1,2}):(\d{2})$/) referring to? It is really driving me crazy…

How to&Answers:

To break down the regex:

^(\d{1,2})  // From the beginning of string (^) capture exactly one or two digits (hours)
:           // must be a colon
(\d{2})$    // Capture exactly two digits which also should be the end of the string

Answer:

In addition to Eriks Klotins’ answer, if you want to understand and/or create your own regex, you can use websites like this one: regex101 or this one regexr.

It’s very powerful and well explained.
I have learned to make regex with these and some youtube tutorials.