Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda