How to prevent repeat spaces in a textarea

Viewed 55

I'm trying to prevent users from inputting repeat spaces in a textarea. Any spaces in a row, I just want the textarea to ignore.

I am trying to simply replace repeats with a single space in my onchange handler by doing this: value.replace(/\s+/g, ' ')

This does work, however, the caret always moves to the end of the textarea. So if I place the caret in the middle of a sentence in a textarea and press space twice, the caret moves to the end of the textarea which is annoying to the user.

I've found I can use event.preventDefault() in the onkeypress handler and it doesn't move the cursor, however, onkeypress does not provide the new value of the input, so I don't know if there are repeat spaces.

Any ideas on how to handle this?

1 Answers

You could slice the textarea value from the beginning to the caret position, and also slice from the caret to the end, then replace those two halves, check the length of the first, put them together, and set the cursor to the checked length:

const textarea = document.querySelector('textarea');
textarea.addEventListener('input', () => {
  const { value } = textarea;
  const position = textarea.selectionStart;
  const p1 = value.slice(0, position).replace(/\s+/g, ' ');
  const p2 = value.slice(position).replace(/\s+/g, ' ');
  const p2Fixed = p1.endsWith(' ') && p2.startsWith(' ') ? p2.replace(/^\s+/, '') : p2;
  textarea.value = p1 + p2Fixed;
  textarea.selectionStart = p1.length;
  textarea.selectionEnd = p1.length;
});
<textarea columns=10 rows=5>
foo bar baz, try adding more spaces here
</textarea>

Related