How to get range of selected text of textarea in JavaScript

耗尽温柔 提交于 2019-12-03 11:55:48

Use the code below or check this fiddle

   function getTextSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }
    alert("start :" + start + " End :" + end);
}

While the original answer may have helped the OP in 2012, things have changed, and this has now become simpler, at least in modern browsers.

You can use the Javascript selectionStart and selectionEnd attributes of the textarea.

Basic Usage:

These are both standard attributes that will work in today's major browsers (Chrome, Safari, Firefox, Opera, Edge, IE).

For example:

console.log(document.getElementById("text").selectionStart,document.getElementById("text").selectionEnd)

will return both the start and end point of the selection in the textarea with the ID text.

Boundary Cases:

If there is no item selected in the textarea, then both the start and end attributes will return the last position of the caret. If the textarea has not recieved focus yet, the attributes will both return a value of 0.

Changing the Selection:

By setting these attributes to new values, you will adjust the active text selection. Thus, you can also use this to select text in a textarea.

Checking if a Selection is in Place:

You can check if there is currently a selection by checking if the values are both different, i.e. if

document.getElementById("text").selectionStart != document.getElementById("text").selectionEnd

is true, then there is a text selection.

References

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!