[Solved] format a 12 digit number in XXXX XXXX XXXX format using javascript


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" />

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