如何计算页面中文本的出现次数

时间:2011-11-30 03:51:25

标签: javascript jquery internet-explorer textrange

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. 

1 个答案:

答案 0 :(得分: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;
}