skip to Main Content

I’m trying to create a regular expression mask to insert the time starting with seconds, minutes and finally the hour.

For example, showing 12:34:56 after typing – 6, 5, 4, 3, 2, 1

I tried creating a regular expression, but I’m not very experienced. If you can help me I would be very grateful
This is my regex that didn’t work:

function timeinvert(v) {
  v = v.replace(/D/g, "");
  v = v.replace(/(d)(d)/, "$2$1")
  v = v.replace(/(d)(d)(d)/, "$3:$2$1")
  v = v.replace(/(d)(d)(d)(d)/, "$4$3:$2$1")
  v = v.replace(/(d)(d)(d)(d)(d)/, "$5:$4$3:$2$1")
  v = v.replace(/(d)(d)(d)(d)(d)(d)d+?$/, "$6$5:$4$3:$2$1")
  // v = v.replace(/(d{2})(d)/, "$1:$2")
  // v = v.replace(/(d{2})d+?$/, "$1")
  return v;
}

3

Answers


  1. It looks like you are trying to invert the time string given in HH:MM:SS format. I am not sure, why you want to use regex, as there are better ways to do it in JS.

    Method 1: Splitting the String
    You can split the string by (:) and invert the date.

    const [hours, minutes, seconds] = v.split(":");
    return `${seconds}:${minutes}:${hours}`;
    

    Method 2: Use JS methods – Not Recommended
    You can use JS date methods to get the minutes, hours and seconds and then return as you please. (This is not recommended as per the comments, but still it is a solution, but not recommended at all)

        const date = new Date(v);
        const hours = date.getUTCHours().toString().padStart(2, '0');
        const minutes = date.getUTCMinutes().toString().padStart(2, '0');
        const seconds = date.getUTCSeconds().toString().padStart(2, '0');
        return `${seconds}:${minutes}:${hours}`; 
    
    Login or Signup to reply.
  2. if you want to create a regular expression mask to insert the time starting with the hours, minutes and finally seconds you can use the following function.

    function timeForward(v) {
        v = v.replace(/D/g, "");
        if (v.length <= 2) {
            return v;
        } else if (v.length <= 4) {
            v = v.replace(/(d{2})(d{2})$/, "$1:$2");
        } else {
            v = v.replace(/(d{2})(d{2})(d{2})$/, "$1:$2:$3");
        }
        return v;
    }
    
    Login or Signup to reply.
  3. Start by inserting : after every other character. Then reverse it.

    function timeinvert(str) {
      time_arr = [];
      for (let i = 0; i < str.length; i++) {
        if (i > 0 && i % 2 == 0) {
          time_arr.push(':');
        }
        time_arr.push(str[i]);
      }
      time_arr = time_arr.reverse();
      return time_arr.join('');
    }
    
    console.log(timeinvert('654321'));
    console.log(timeinvert('54321'));
    console.log(timeinvert('4321'));
    console.log(timeinvert('321'));
    console.log(timeinvert('21'));
    console.log(timeinvert('1'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search