文字列の出現回数をカウントするには?

特定の文字列が他の文字列の中に出現した回数をカウントするにはどうしたらよいでしょうか。例えば、Javascriptでこんなことをしようとしています。

var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
ソリューション

正規表現のgglobalの略)は、最初に出てくるものだけを探すのではなく、文字列全体を検索することを意味します。これは is に2回マッチします。

var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);

そして、マッチしたものがなければ、0を返します。

var temp = "Hello World!";
var count = (temp.match(/is/g) || []).length;
console.log(count);
解説 (17)
function countInstances(string, word) {
   return string.split(word).length - 1;
}
解説 (10)

このような関数を定義するには、matchを使用します。

String.prototype.count = function(search) {
    var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
    return m ? m.length:0;
}
解説 (2)