How to find start and end positions of select text in Javascript?

I am trying to find the text start and end of the selection. So, in the next text, if I chose “world!”, “What a beautiful” from the inside “Hello world! What a beautiful day!”, I should get 7 as the starting coordinate, and 24 as the ending coordinate assuming zero index.

How is this achievable?

EDIT: I am looking to find a selection of text that is not inside any <input> or <textarea> elements.

EDIT: Decided to use disabled <textarea>s

+4
source share
3 answers

I use this:

 /* Returns 3 strings, the part before the selection, the part after the selection and the selected part */ function getSelected() { var u = editor.val(); var start = editor.get(0).selectionStart; var end = editor.get(0).selectionEnd; return [u.substring(0, start), u.substring(end), u.substring(start, end)]; } 

where is the editor $("#editor") or any other identifier that your textarea / input field may have.

Using:

 var select = getSelected() editor.val(select[0] + '<h1>'+ select[2] + '</h1>' + select[1]); 

Flips the selected text to H1. If nothing is selected, it will simply add an empty H1, but you can add checks and functions to your liking.

** Not tested in all browsers, works in Chrome, although **

+2
source

This is possible, but a little complicated with contenteditable HTML content (as opposed to text inside an <input> or <textarea> element). Here is a simple cross-browser implementation:

fooobar.com/questions/21551 / ...

+2
source

But I know that the jQuery plugin is aimed at your problem and more - https://github.com/localhost/jquery-fieldselection

0
source

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


All Articles