如何查找突出显示的字符串的出现次数,以及出现的次数?

时间:2014-12-05 18:12:23

标签: javascript jquery web

正如标题所说,我说有一些网站在某个div中有文字,有没有办法突出显示它的某些部分并知道它出现了什么?如果一个文本出现4个单词“something”,我突出显示第3个,我如何使用Javascript / JQuery获取该信息?

2 个答案:

答案 0 :(得分:1)

你可以:

  1. 获得突出显示的文字Get the Highlighted/Selected text
  2. 获取父元素的所有文本,或页面的所有文本,或者您想要获取文本的所有文本
  3. 分词
  4. 检查同一个词的出现

答案 1 :(得分:1)

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

这是一种似乎有用的方法。突出显示所需的字符串,当您单击该按钮时,它将提醒div中该突出显示的单词的索引。

标记:

<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" />

和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);
    });
});