-1

I have this regex in my code:

const date = new Date();
const result = date.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, '$1$3');
console.log(result);
//"8:58 AM"

In some cases (an android emulator) it shows "08:58". I'm not good on regex:

replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, '$1$3')

what it means that replace?

pmiranda
  • 4,757
  • 7
  • 35
  • 74

2 Answers2

3

This regex removes the second group aka (:[\d]{2}) which in your new date exemple is the seconds of the time new Date().toLocaleTimeString() outputs 15:09:22 (at the time of writing)

note that

new Date().toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, '$1')

is enough to write hh:mm,

EDIT : the $3 is specialy usefull for 12-based hour system (AP/PM) as it print the rest of the string (aka PM or AM), you are calling toLocaleTimeString() that why it is local and dependant of the system

There exist other solution to write hh:mm eg

const date = new Date();
console.log(`${(''+date.getHours()).padStart(2, '0')}:${(''+date.getMinutes()).padStart(2, '0')}`);
CharybdeBE
  • 1,358
  • 15
  • 28
  • Very nice. The last console.log shows time as `9:8` though. Very informative answer btw. – pmiranda Jul 17 '20 at 13:22
  • 1
    Thanks ive edited by casting the number to string, then calling padstart to add zeroes if needed (its the afternoon her ei forgot to think :) ) – CharybdeBE Jul 17 '20 at 13:26
2

This regex removes two specific number in the given string.

Example :

const test = '11111:22:33 whatever';

const rep = test.replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, '$1$3');

console.log(rep);

https://regex101.com/r/TlUuMF/1

Orelsanpls
  • 18,380
  • 4
  • 31
  • 54