0
var textRange = document.body.createTextRange();
  textRange.collapse(true);
  if( textRange.findText(tex)) {
    textRange.execCommand("BackColor", false, "yellow");
}

上面的代码非常适合在 IE 中搜索文本并突出显示它,但我想做一些修改来计算出现次数。像下面

textRange.findText(tex).WhichMethod()  Should i use to return me count of occurrences. 
4

1 回答 1

0

如果您只想计算特定模式的实例数,那么类似以下内容应该适合:

function countString(s) {
  var re = new RegExp(s, 'gi');
  var b = document.body;

  // Make an assumption about support for textContent and inerText
  var text = typeof b.textContent == 'string'? b.textContent : b.innerText;
  var matches = text.replace(/\s+/g, ' ').match(re);

  return matches? matches.length : 0;
}
于 2011-11-30T04:09:50.627 回答