Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!