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];
}
}}