A
A
Andrey Filippov2016-04-16 18:38:59
JavaScript
Andrey Filippov, 2016-04-16 18:38:59

How to get selected text + n characters on sides?

I found this function to get the selected text:

function getSelectionText() {
    var text = "";

    if (window.getSelection) {
        text = window.getSelection(5).toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }

    return text;
}

but I can't figure out how to get what is selected by the user + 10 (for example) characters on the sides. Tell me, please, where to dig.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Babichev, 2016-04-21
@andrysha-dev

cdd579161b1842f8b0c58960feb437bc.png
Here is a simple example, no checks. For document.selection is done in a similar way.

function getSelectionText(d) {
    var string = window.getSelection();
    return string.baseNode.data.substring(string.anchorOffset - d, string.focusOffset + d);
}
var string = getSelectionText(10);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question