Search code examples
javascriptregexstringtimeregex-group

How can I extract Time from this string in javascript?


I have this String

var data = "Mon 08:30am - 04:30pm"

and I need it in this form

//expected String remove am pm and convert pm timing into 24 hrs time format
Result = 8:30-16:30

How Can I do it with Regex in Javascript .I tried it using substring but thats not the correct way.

I tried it with this but didnt find this correct way

var amHourFrom = parseInt(details[0].data.substring(4, 2)));    
var amMinuteFrom = parseInt(details[0].data.substring(7,2)));   
var pmHourFrom = parseInt(details[0].data.substring(14, 2)));   //04
var pmMinuteFrom = parseInt(details[0].data.substring(17,2)));  //30

if(details[0].data.substring(19,2)=="pm"){
{pmHourFrom = hourFrom +12;     //04+12 = 16    
}
var Str= amHourFrom + ":" + amMinuteFrom "-" + pmHourFrom+ ":" + pmMinuteFrom;
var result = Str.replace(/^(?:00:)?0?/, '');

I want to do it with some other way


Solution

  • We can try the following regex replacement approach:

    var data = "Mon 08:30am - 04:30pm";
    var times = data.replace(/(\d{2}):(\d{2})([ap]m)/g, (m, x, y, z) => z === "am" ? x + ":" + y : "" + (12 + parseInt(x)) + ":" + y)
                    .match(/\d{2}:\d{2}/g)
                    .join("-");
    console.log(times);

    The first chained call to replace() converts the hours component to 24 hour time by adding 12 hours in the case of pm times. Then we find all time matches, and join together by dash in the final string output.