0

I have this simple input with the text inside:

document.querySelector('.input').value = 'Double click on words without extra space'
.input {
  width: 400px
}
<input type="text" class="input" placeholder="">

Except the last word in the input if you double-click any other words it will be selected with an extra space afterwards.

Is there any solution so that double-clicking any word in the input only select the whole word without that space?

Raol mAX
  • 91
  • 5
  • Related: https://superuser.com/questions/282568/is-there-a-way-to-not-select-whitespace-after-a-word-when-double-clicking – Anurag Srivastava Jul 27 '23 at 09:30
  • 2
    Does this answer your question? [In browsers: Select only the selected word, not with the space after it](https://stackoverflow.com/questions/57154753/in-browsers-select-only-the-selected-word-not-with-the-space-after-it) Please search around before asking a question that has been asked multiple times already – Mihai T Jul 27 '23 at 09:36

1 Answers1

0

You can modify the text selection using Selection#modify() with parameters alter: "extend", direction: "left" and granularity: "character".

From developer.mozilla.org:

The Selection.modify() method applies a change to the current selection or cursor position, using simple textual commands.

const inputElement = document.querySelector('.input');
inputElement.value = 'Double click on words without extra space';

inputElement.addEventListener('dblclick', function(event) {
  const selection = window.getSelection();
  const text = selection.toString();

  if (/\s+$/.test(text)) { // Check if there is a trailing whitespace
    selection.modify("extend", "left", "character");
  }
});
.input {
  width: 400px
}
<input type="text" class="input" placeholder="">
Behemoth
  • 5,389
  • 4
  • 16
  • 40