After regex is called cursor goes to end. So I tried that fix, that also did not work properly. How can that be fixed? My target: if field empty and digits is typed > cursor at end, if back to add or delete any digit > cursor at proper position(not at end)
document.getElementById('target').addEventListener('input', function (e) {
var target = e.target,
position = target.selectionStart; // Capture initial position
target.value = target.value.replace(/\B(?=(\d{3})+(?!\d))/g, "-");// This triggers the cursor to move.
target.selectionEnd = position; // Set the cursor back to the initial position.
});