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

270
Visualizações
Javascript - Regex replace number with HH:MM

I am trying to replace 4 numbers with a time format. For example if user enters 1234 to be replaced with 12:34

I have found that this regex does this job

let myString = "1234";
myString.replace(/\b(\d{2})(\d{2})/g, '$1:$2')

But now I am trying to figure out how to use this with cases like

94 - this should be replaced with 23 then it does same for time after the colon

01:74 - this should be replaced with 01:59

I have found a regex which does that ^([0-1]?[0-9]|2[0-3]):[0-5][0-9], but I am not able to figure out how to combine this with .replace

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You will need to match on the first and second pair of digits and then bound them by their max values. Once you have the bounded values, you can pad the numbers and join them with a colon.

const toTimeString = (value) => {
  const
    [, hours, minutes] = value.match(/^(\d{2})(\d{2})$/),
    hour = `${Math.min(+hours, 24)}`.padStart(2, '0'),
    minute = `${Math.min(+minutes, 59)}`.padStart(2, '0');
  return `${hour}:${minute}`;
};

console.log(toTimeString('0174')); // 01:59
console.log(toTimeString('3412')); // 24:12

Now, here is a replacer example:

const minPad = (value, min) => `${Math.min(value, min)}`.padStart(2, '0');

const toTimeString = (value) =>
  value.replace(/\b(\d{2})(\d{2})\b/g, (match, hours, minutes) =>
    `${minPad(hours, 24)}:${minPad(minutes, 59)}`);

console.log(toTimeString('0174 3412')); // 01:59 24:12

about 4 years ago · Juan Pablo Isaza Relatório

0

There is an overload of replace which takes a function which you can use to do any logic you need, such as:

let myString = "1234";

function formatTime(input){
  return input.replace(/\b(\d{2})(\d{2})/, (_,hh,mm) => {
    return `${Math.min(hh,24)}:${Math.min(mm,59)}`
  })
}

console.log(formatTime("1234"));
console.log(formatTime("3412"));
console.log(formatTime("0174"));

about 4 years ago · Juan Pablo Isaza Relatório

0

I do not see any good reason to use regex in your case.
Just a simple function will do the job.

function transformTextToHHMMTimeFormat(text) {
  const firstNumber = Number(text.slice(0, 2))
  const secondNumber = Number(text.slice(2, 4))
  const hour = Math.min(firstNumber, 24)
  const minute = Math.min(secondNumber, 59)

  return `${hour}:${minute}`
}
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