Search code examples
javascriptjqueryregexnumber-formatting

format a 12 digit number in XXXX XXXX XXXX format using javascript


I have an input field in which the user types a 12 digit number and I need to show it in the format XXXX XXXX XXXX (sapce after every 4 digits). How do I achieve it in javascript so that it works well with backspaces, editing in between etc.

This is what I have written but it misbehaves when I edit the input from somewhere in between.

function format_outlet_id(value) {
  var content = value.value.trim();
  var length = content.length;
  var key = event.keyCode || event.charCode;
  if (!(key == 8 || key == 32 || key == 46)) {
      if (length == 12) {
          data = content.match(/.{1,4}/g);
          value.value = data[0] + " " + data[1] + " " + data[2];
      }
  }}

Solution

  • You can use selectionEnd to control the position of cursor

    var target = document.querySelector('.creditCardText');
    
    target.addEventListener("keyup", function() {
      var position = target.selectionStart;
      var prevVal = target.value;
      var newVal = prevVal.split(" ").join(""); // remove spaces
      if (newVal.length > 0) {
        newVal = newVal.match(new RegExp('.{1,4}', 'g')).join(" ");
      }
      target.value = newVal;
      
      for (var i = 0; i < position; i++) {
        if (prevVal[i] != newVal[i]) {
          target.selectionEnd = position + 1;
          return;
        }
      }
      target.selectionEnd = position;
    });
    <input type="text" class="creditCardText" />