Stop cursor from jumping to end of input field in javascript replace

Solution 1:

In addition to gilly3's answer, I thought someone might find it useful to see an actual code snippet.

In the example below, the selectionStart property is retrieved from the input element prior to the JavaScript string manipulation. Then selectionStart is set back to the initial position after the manipulation.

Depending on what you're trying to achieve, you could also access selectionEnd in place of selectionStart, and set a range: setSelectionRange(start, end).

document.getElementById('target').addEventListener('input', function (e) {
  var target = e.target,
      position = target.selectionStart; // Capture initial position
  
  target.value = target.value.replace(/\s/g, '');  // This triggers the cursor to move.
  
  target.selectionEnd = position;    // Set the cursor back to the initial position.
});
<p>The method <code>.replace()</code> will move the cursor's position, but you won't notice this.</p>
<input type="text" id="target" />

Solution 2:

You'll have to manually put the cursor back where you want it. For IE9, set .selectionStart and .selectionEnd (or use .setSelectionRange(start, end)). For IE8 and earlier, use .createTextRange() and call .moveStart() on the text range.