3

When you select a word by double click in browsers, it usually selects the word and a space after it.

How I could make the selection capture only the word, without the space?

Note: The behavior I am talking about is in Google translate, go there, search for the translation of any word, then in the Examples section for example, select any word, you will find it selects exactly the word without the space after it.

Update

I was asking because we were developing an editor based on slatejs, and we were adding some marks dynamically at the beginning, but when the user try to select the word to edit the mark, it doesn't get selected because the selection should be on the word only.

Marwan
  • 627
  • 1
  • 7
  • 15

4 Answers4

1

You can double click the mouse(as you are already doing), don't let the mouse go and move it a bit to right.

enter image description here

Hackinet
  • 3,252
  • 1
  • 10
  • 22
0

Your best bet is to apply the String function trim() to the copied text which will remove whatever trailing or leading white space characters you’ve grabbed.

Jimmay
  • 582
  • 5
  • 10
0

I'm not sure what you're trying to accomplish with it but if user training is an option I want to point out that if you double click and hold, then pull back, it will keep the word selected and deselect the space.

If you are capturing the the selection in code, then you could trim the data as suggested by Jimmay

Seth
  • 972
  • 1
  • 7
  • 18
0

Very good question. Still a problem in Chrome and probably other browser. No solution so far. Probably you have to get the selected word by Javascript and then see if the last character is a space, then reset the selection with textfield[0].selectionStart and textfield[0].selectionEnd - 1.

Simple implementation with Jquery:

$('body').on('dblclick', 'textarea', function()
{
    let textfield = $(this);

    let start = textfield[0].selectionStart;
    let end = textfield[0].selectionEnd;

    // check if text is selected
    if (isTextSelected(textfield[0]))
    {
        let text_selected = textfield.val().substring(start, end);

        var last_char = text_selected.substr(text_selected.length - 1);

        // mouse doubleclick marks whitespace after word by default, we just want the word
        if (last_char == ' ')
        {
            textfield.prop('selectionStart', start);
            textfield.prop('selectionEnd', end - 1);
        }
    }
});
// https://stackoverflow.com/questions/9065828/javascript-check-if-text-selected
function isTextSelected(input)
{
    var startPos = input.selectionStart;
    var endPos = input.selectionEnd;
    var doc = document.selection;
 
    if (doc && doc.createRange().text.length != 0)
    {
       return true;
    }
    // extra check
    if (!input.value)
    {
        return false;
    }
    else if (!doc && input.value.substring(startPos,endPos).length != 0)
    {
       return true;
    }
    return false;
}
Avatar
  • 14,622
  • 9
  • 119
  • 198