user1025725
user1025725

Reputation: 192

How do I find how many occurences are there of a highlighted string, and which occurence is it?

As the title says, say I have some website with a text inside some div, is there a way to highlight some part of it and know which occurence it is? If a text has 4 occurences of the word "something", and I highlight the 3rd, how do I get that information using Javascript/JQuery?

Upvotes: 1

Views: 47

Answers (2)

sbonkosky
sbonkosky

Reputation: 2557

http://jsfiddle.net/g09g35xa/6/

Here's a method that seems to work. Highlight the string you want and when you click the button it will alert the index of that highlighted word in the div.

Markup:

<div id="theDiv">
<p>The quick brown quick fox jumps over the lazy dog</p>
</div>
<br />
<input id="findIndex" type="button" value="Find Index Of Highlighted String" />

And the JS:

function getSelectedHTML() {
    try {
        if (window.ActiveXObject) {
            var c = document.selection.createRange();
            return c.htmlText;
        }

        return getSelection().getRangeAt(0).toString();
    } catch (e) {
        if (window.ActiveXObject) {
            return document.selection.createRange();
        } else {
            return getSelection();
        }
    }
}

function surroundSelectedElement() {
    var nNd = document.createElement("span");
    nNd.setAttribute("id","actualSelectedElement");
    var w = getSelection().getRangeAt(0);
    w.surroundContents(nNd);
}

$(function() {
    // save originalHtml to reset later
    var originalHtml = $("#theDiv").html();
    $("#findIndex").click( function() {        
        // get the selected string
        var selectedText = getSelectedHTML();
        if(selectedText === '')
            return;

        // surround the selected area with a span, id = actualSelectedElement
        surroundSelectedElement();

        // build Regex to find all occurrences of string that was selected
        var re = new RegExp(selectedText, "g");

        // replace instances of string with span tags, class = selectedText
        $("#theDiv").html($("#theDiv").html().replace(re, "<span class='selectedText'>" + selectedText + "</span>"));

        // the actual one selected is contained within a span with id=actualSelectedElement, so get all spans with class=selectedText and find the index of the one with the extra span actualSelectedElement
        var index = $('span.selectedText').index($('span#actualSelectedElement span.selectedText'));

        alert(index);

        // reset the html back to original
        $("#theDiv").html(originalHtml);
    });
});

Upvotes: 1

dm03514
dm03514

Reputation: 55972

you could:

  1. get highlighted text Get the Highlighted/Selected text
  2. get all text of parent element, or all text of page, or all text of whatever you want to get the text of
  3. split words
  4. check for occurances of same word

Upvotes: 1

Related Questions