'Javascript: Input the duration of movie and return number of hours

I'm new to react and as practise, I'm building a react app. The form has a duration input which expects the data either in minutes or hours eg. 132m or 2.5h. The function should return the number of hours based on the input or show error in alert that "Duration is in invalid format".

How can I go about this? The value is string and so I was thinking of using duration.includes('m') or duration.includes('h') but the problem is it will accept "1h32" for example. I also want to know how float can be extracted from the string?



Solution 1:[1]

I would suggest using a regular expression to parse the numbers from the given input. Next, you have to convert the strings to a number. Last, pass the result to a calculate function to convert minutes to hours

const input = '132m';
// const input = '2.5h'
// const input = '1h32';

function parseDuration(input) {
  const { groups } = input.match(/((?<hours>\d+(\.\d+)?)h)?((?<minutes>\d+)m?)?/);

  const hours = Number(groups.hours) || 0;
  const minutes = Number(groups.minutes) || 0;

  return {
    hours,
    minutes,
  };
}

function durationToHours(hours, minutes) {
  return hours + minutes / 60;
}

const parsedDuration = parseDuration(input);
const hours = durationToHours(parsedDuration.hours, parsedDuration.minutes);

hours; // 2.2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marcobiedermann