Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda