MePo
MePo

Reputation: 1074

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

Upvotes: 0

Views: 614

Answers (3)

Krystian Sztadhaus
Krystian Sztadhaus

Reputation: 494

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}`
}

Upvotes: 1

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

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

Upvotes: 2

Jamiec
Jamiec

Reputation: 136094

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"));

Upvotes: 1

Related Questions