This regex pattern matches time in either h:mm or hh:mm format. It starts with an optional 0 for single-digit hours, followed by either 1 or 2 for double-digit hours. Then, a colon is required, followed by minutes ranging from 00 to 59. The \b ensures that the match is a whole word.
const timeRegex = /\b(?:1[0-2]|0?[1-9]):[0-5][0-9]\b/;
const time = '9:30';
if (time.match(timeRegex)) {
console.log('Valid time format');
} else {
console.log('Invalid time format');
}
Copiar