Skip to content Skip to sidebar Skip to footer

Javascript Time Conversion Regexp

I have a method using regular expressions in .Net to convert time from e.g. '1h 20m' format to double. Here is it. public static double? GetTaskHours(this string tmpHours) { Doub

Solution 1:

The String.match method will return only an array of the complete matches, not of any groups. Use the Regex.exec method to get all the groups:

functiongetHours(value) {
    var myArray = (/^((\d+)(h|:))?\s*((\d+)m?)?$/g).exec(value);
    var hours = myArray[2];
    var minutes = myArray[5];
    returnNumber(hours) + Number(minutes) / 60;
}

Solution 2:

I suppose you don't really need the g modifier. So you can also try this: (just g removed)

functiongetHours(value) {
  var myArray = value.match(/^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$/);
  var hours = myArray[2];
  var minutes = myArray[5];
  returnNumber(hours) + Number(minutes) / 60;
}
getHours("3h 30m")

Post a Comment for "Javascript Time Conversion Regexp"