0

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

4
  • 1
    Why 24:12? Maybe 00:12? Commented Dec 15, 2021 at 19:20
  • Well you are going to have to use a function in replace and add logic to change the output. There is nothing you can do with a string output that can do it. Commented Dec 15, 2021 at 19:22
  • To merely insert a colon (not your entire question) you can replace a zero-width match (think of it as between two successive characters) with a colon: myString.replace(/(?<=\b\d{2})(?=\d{2}\b)/g, ':'). Demo. Hover your cursor over each element of the regular expression at the link to obtain an explanation of its function. Commented Dec 15, 2021 at 20:21
  • @WiktorStribiżew you are right, overlooked that Commented Dec 16, 2021 at 10:51

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, that helped me a lot. But I have a one more thing, let say user starts to write 25 or 29 or even 99, how would I replace that to 23 for max hours ( at first two digits ), then after it replaces like in your example
@MePo you would simply add a key listener to an input and just validate the text each time the user types.
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.