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 に答える