Insert a character every nth index.

Insert a specific character to a form field every nth index.

by Donavon Lerman

HTML

<input name="myField" id="myField" type="text">

JavaScript

// get field
var myField = document.getElementById("myField");

// add listener to field
myField.addEventListener("keyup", function(e) {
  // initialize values
  var character  = ','; // character to add
  var index      = 3;   // index to add character at
  var from			 = 'right'; // start index from right / left
  
  var newValue   = '';
  
  // remove character from value
  newValue  = myField.value.replace(new RegExp(character, 'g'),'');
  
  // add character at index
  newValue  = addCharacter(newValue, character, index, from);
  
  // replace current value with newValue
  if(newValue) {
  	document.getElementById("myField").value = newValue;
  }

}, false);


// function to insert value at specific index
function addCharacter(str, character, index, from) {
  // convert the str to an array
  var strArray = str.split("");

  // loop through array
  for (var i = 0; i < str.length; i++) {
    // find array index matching index and insert character
    if(i % index == 0) {
      strArray.splice(i + 1, 0, character);
    }
  }

  return strArray.join("");
}