// 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("");
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.