Search code examples
javascriptlocal-storageselectedtext

Javascript: How to find which instance of a particular text (e.g. a word which occurs more than once in a paragraph) was selected in a long paragraph?


I plan to develop a web application. In a part of the application, the user selects a text from a paragraph, and then click a save button.

For example, the user selects "apple" (shown in bold) from the following text:

An apple is the pomaceous fruit of the Malus domestica tree of the rose family (Rosaceae). It is one of the most widely cultivated tree fruits, and the most widely known of the many members of genus Malus that are used by humans. Malus domestica tree is often simple called as an apple tree.

When the user clicks the save button, JS should add it to an object as a key-value pair. The value should be the selected text (apple in this case) while the key should be something which indicates which instance of the selected text it is. The reason is that "apple" occurs again as the second last word in the given paragraph.

Something like:

var object = new Object();
var textString = window.getSelection().toString();
object.indicator = textString;

I'd like to keep track of which instance of "apple" (i.e. the selected text) did the user select. So is it possible to keep tract of it?

The next steps are to store this object, so that when the user launches this page again or comes back here, we tell him what he had already selected.


Solution

  • This example doesn't get which instance was selected (1st or 2nd), but it does get the offset index within the string, which should suffice.

    <div id="content">An apple is the pomaceous fruit of the Malus domestica tree of the rose family (Rosaceae). It is one of the most widely cultivated tree fruits, and the most widely known of the many members of genus Malus that are used by humans. Malus domestica tree is often simple called as an apple tree.</div>
    
    <button onclick="saveSelection()">Save Selection</button>
    
    <script>
        function saveSelection() {
            var selection = window.getSelection();
            var selectedText = selection.toString();
            var selectionInfo = {
                offset: selection.anchorOffset,
                length: selectedText.length,
                text: selectedText
            };
            localStorage["lastSelection"] = JSON.stringify(selectionInfo);
        }
    
        window.onload = function () {
            var selectionJSON = localStorage["lastSelection"];
            if (selectionJSON) {
                selection = JSON.parse(selectionJSON);
                alert(JSON.stringify(selection) + "\n" + document.getElementById("content").innerText.substr(selection.offset, selection.length));
            }
        };
    </script>