skip to Main Content

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?

2

Answers


  1. 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="">
    Login or Signup to reply.
  2. Probably a workaround using setSelectionRange():

    document.querySelector('.input').value = 'Double click on words without extra space';
    
    function handleDoubleClick(event) {
      const input = event.target;
      const cursorPosition = input.selectionStart;
      
      //split the input value into an array
      const words = input.value.split(' ');
      let start = 0;
      let end = 0;
    
      //find the word that contains the cursor position
      for (let i = 0; i < words.length; i++) {
        end = start + words[i].length;
        if (cursorPosition >= start && cursorPosition <= end) {
          break;
        }
        start = end + 1; //add 1 to skip the space after the word
      }
      //set the selection range to select the whole word without the extra space
      input.setSelectionRange(start, end);
    }
    
    const inputElement = document.querySelector('.input');
    inputElement.addEventListener('dblclick', handleDoubleClick);
    .input {
      width: 400px
    }
    <input type="text" class="input" placeholder="" oninput="processInput()">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search