Set the selection range to the "position" that you created, and if you added a "-", you increase the position, for example:
document.getElementById('target').addEventListener('input', function (e) {
var target = e.target,
position = target.selectionStart;
var old = target.value;
target.value = target.value.replace(/\B(?=(\d{3})+(?!\d))/g, "-");
if(old != target.value)
position++;
target.setSelectionRange(position, position);
});
source
share