如何获取所选单词在 Javascript 中的出现次数

How to get the occurrence of the selected word in Javascript

假设我有一个 DIV 包含文本,如下所示:

<div>
Hello world

test

Hello world

test 2

Hello world
</div>

我在select输入文本时获取单词的函数是:

function getWord() {
    var txt = document.getSelection();
    var txtRange = txt.getRangeAt(0);
    return txtRange;
}

假设我 select 中间的“Hello world”,这是第 2 次出现。我如何获得出现次数,在本例中为 2?

您可以试试下面的代码。

document.addEventListener('selectionchange', (evt) => {
  var selection=document.getSelection();
  var selectedText = selection.getRangeAt(0).toString();
  var divText=document.getElementById("mydiv").innerText;
  var totalOccurance=(divText.match(new RegExp(selectedText, "g")) || []).length;
  console.log(totalOccurance)
});
<div id="mydiv">
Hello world

test

Hello world

test 2

Hello world
</div>

如果你也想忽略输入那么你下面的代码

document.addEventListener('selectionchange', (evt) => {
  var selection=document.getSelection();
  var selectedText = selection.getRangeAt(0).toString().replace(/\n/g, " ");
  var divText=document.getElementById("mydiv").innerText.replace(/\n/g, " ");
  var totalOccurance=(divText.match(new RegExp(selectedText, "g")) || []).length;
  console.log(totalOccurance)
});
<div id="mydiv">
Hello world

test

Hello world

test 2

Hello world
</div>

如果您想找出您选择的是哪一个词,请使用此示例

示例 3

document.addEventListener('selectionchange', (evt) => {
  var selection=document.getSelection();
  if(selection){
  var selectedText = selection.getRangeAt(0).toString().replace(/\n/g," ").replace(/ +(?= )/g,'');
  var divText=document.getElementById("mydiv").innerText.replace(/\n/g," ").replace(/ +(?= )/g,'');
  if(selectedText){
var reg=new RegExp(selectedText, "g");
var array1 = reg.exec(divText)
var index=[];
while (array1 !== null) {
  index.push(array1.index);
  array1 = reg.exec(divText)
}
var position=selection.anchorOffset-1;
var p=index.filter(x=>x<=position)
console.log(p.length);
   }
  }
});
   
<div id="mydiv">
Hello world

test

Hello world

test 2 

Hello world
</div> 

Codepen Link

https://codepen.io/hackersourabh/pen/dyMWKVm?editors=1011

概念是获取所选字符串的索引,然后计算出现索引。 Fiddle Link

<div id="mydiv" onmouseup="alert(getOccuranceIndex(this));"
onmousedown="prepare(this)>
Hello world

test

Hello world

test 2

Hello world
</div>


var getOccuranceIndex= (function() {

    function getSel() {
        var sel = null;
        if (
            typeof document.selection != "undefined" &&
            document.selection &&
            document.selection.type == "Text"
        ) {
            sel = document.selection;
        } else if (
            window.getSelection &&
            window.getSelection().rangeCount > 0
        ) {
            sel = window.getSelection();
        }
        return sel;
    }

    function createRangeFromSel(sel) {
        var rng = null;
        if (sel.createRange) {
            rng = sel.createRange();
        } else if (sel.getRangeAt) {
            rng = sel.getRangeAt(0);
            if (rng.toString() == "") rng = null;
        }
        return rng;
    }

    return function(el) {
        var sel = getSel(),
            rng, r2, i = -1;
        if (sel) {
            rng = createRangeFromSel(sel);
            if (rng) {

                if (rng.parentElement) {
                    if (rng.parentElement() == el) {
                        r2 = document.body.createTextRange();
                        r2.moveToElementText(el);
                        r2.collapse(true);
                        r2.setEndPoint("EndToStart", rng);
                        i = r2.text.length;
                    }
                } else {
                    if (
                        rng.startContainer &&
                        rng.endContainer &&
                        rng.startContainer == rng.endContainer &&
                        rng.startContainer == rng.commonAncestorContainer &&
                        rng.commonAncestorContainer.parentNode == el
                    ) {    
                        i = rng.startOffset;
                    }
                }
            }
        }
                if(i<1) return 1;
        var actualString = el.innerHTML;
                var target = getSel().toString();
console.log(target);
            var reg = new RegExp(target, 'gi');
                var resArr = actualString.substring(0,i-1).match(reg);
            if(resArr==null) return 1; //this is the first occurance;
            return resArr.length+1;
    };

})();

function prepare(el) {
    if (el.normalize) {
        el.normalize();
    }
}

这很有帮助https://bytes.com/topic/javascript/answers/153164-return-selectionstart-div

我有解决办法:

function getWord() {
    var txt = document.getSelection();
    var txtRange = txt.getRangeAt(0);
    return txtRange;
}

var t = getWord();
var text = document.getElementsByClassName("content")[0];
var precedingRange = document.createRange();
    precedingRange.setStartBefore(text.firstChild);
    precedingRange.setEnd(t.startContainer, t.startOffset);

var textPrecedingSelection = precedingRange.toString();
var count = (textPrecedingSelection.match(new RegExp(t.toString().trim(), 'gi')) || []).length + 1;

alert("Word occurrence: " + count);