How does js get the index of selected paragraphs of text?

how do I get the start and end indexes of the selected text in the current text?

clipboard.png
can now get the text, but can"t get the index of the selected text in the current paragraph. Which god knows?


use getSelection to get information about the selected text, including the start and end points.

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id="example">
    

41332(Sng Ee Tze)34(Nadim Van Der Ros)5""331""5

<button id="button"></button> </div> </body> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script> <script> var oBtn = document.getElementById("button"); oBtn.onclick = function() { var userSelection, text; if (window.getSelection) { // userSelection = window.getSelection(); } else if (document.selection) { //IE Opera userSelection = document.selection.createRange(); } console.log(userSelection); if (!(text = userSelection.text)) { text = userSelection; } alert(`:${text},${userSelection.anchorOffset}-${userSelection.focusOffset}`); }; </script> </html>

reference: https://www.zhangxinxu.com/wo.


const allString = `dklasjdlkajslkdjalskjdlkasjdklasdhbasgduyquiw`;
const selectedString = `jdklas`;
const startIndex = allString.indexOf(selectedString);
const endStartIndex = startIndex >= 0 ? startIndex + selectedString.length : -1;
The only problem with

is that if the selected text is duplicated in the full text
, for example, if the full text is "I "
, if the selected text is "", I don't know which paragraph it is

.
Menu