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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With