Problem
We are required to write a JavaScript function that takes in a time string in “HH:MM:SS” format.
But there was a problem in addition, so many of the time strings are broken which means the MM part may exceed 60, and SS part may as well exceed 60.
Our function should make required changes to the string and return the new rectified string.
For instance −
"08:11:71" -> "08:12:11"
Example
Following is the code −
const str = '08:11:71'; const rectifyTime = (str = '') => { if(!Boolean(str)){ return str; }; const re = /^(\d\d):(\d\d):(\d\d)$/; if (!re.test(str)){ return null; }; let [h, m, s] = str.match(re).slice(1,4).map(Number); let time = h * 3600 + m * 60 + s; s = time % 60; m = (time / 60 |0) % 60; h = (time / 3600 |0) % 24; return [h, m, s] .map(String) .join(':'); }; console.log(rectifyTime(str));
Output
Following is the console output −
08:12:11