3

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) {
  Double taskHours = 0;
  if (!string.IsNullOrEmpty(tmpHours) && !double.TryParse(tmpHours, out taskHours)) {
    var match = Regex.Match(tmpHours, @"^(?=\d)((?<hours>\d+)(h|:))?\s*((?<minutes>\d+)m?)?$", RegexOptions.ExplicitCapture);
    if (match.Success) {
      int hours;
      int.TryParse(match.Groups["hours"].Value, out hours);
      int minutes;
      int.TryParse(match.Groups["minutes"].Value, out minutes);
      taskHours = (double)hours + (double)minutes / 60;
    }
  }
  return Math.Round(taskHours, 3);
}

Now I need the same using Javascript. I tried to convert the regex according to http://www.w3schools.com/jsref/jsref_regexp_nfollow.asp but all my atempts failed. I'm very poor in regular expressions.

Here is my JS attempt.

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

Is it correct?
Can you please show me the way?

Regards, Dmitry.

2 Answers 2

2

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:

function getHours(value) {
    var myArray = (/^((\d+)(h|:))?\s*((\d+)m?)?$/g).exec(value);
    var hours = myArray[2];
    var minutes = myArray[5];
    return Number(hours) + Number(minutes) / 60;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.