Make sure the range object does not start or end in the middle of the word

My application requires heavy use of ranges ( https://developer.mozilla.org/en/DOM/range ). In particular, users often select text and then manipulate it. Sometimes users accidentally select text containing a fragment of a word, and this leads to strange results.

I would like to be able, given the range, to check whether it starts or ends in the middle of a word, and then, if so, expand it so that it includes the whole word that it started / ended in the middle.

+3
source share
2 answers

, , . , onmouseup. , , . , , , . , :

/\s+/
+1

? Kinda hacky, Firefox , , . , :

function fixRange(range)
{
    var rangeString = range.toString();
    try
    {
        while (rangeString[0] != " ")
        {
            range.setStart(range.startContainer, range.startOffset - 1);
            rangeString = range.toString();
        }
        range.setStart(range.startContainer, range.startOffset + 1);
    } catch (e) {}
    try
    {
        while (rangeString[rangeString.length - 1] != " ")
        {
            range.setEnd(range.endContainer, range.endOffset + 1);
            rangeString = range.toString();
        }
        range.setEnd(range.endContainer, range.endOffset - 1);
    } catch (e) {}
    return range;
}

( ):

var selection = window.getSelection();
selection.addRange(fixRange(selection.getRangeAt(0)));
+1

Source: https://habr.com/ru/post/1715842/


All Articles