特定の文字列が他の文字列の中に出現した回数をカウントするにはどうしたらよいでしょうか。例えば、Javascriptでこんなことをしようとしています。
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
正規表現のg
(globalの略)は、最初に出てくるものだけを探すのではなく、文字列全体を検索することを意味します。これは 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);