特定の文字列が他の文字列の中に出現した回数をカウントするにはどうしたらよいでしょうか。例えば、Javascriptでこんなことをしようとしています。
var temp = "This is a string."; alert(temp.count("is")); //should output '2'
正規表現のg(globalの略)は、最初に出てくるものだけを探すのではなく、文字列全体を検索することを意味します。これは is に2回マッチします。
g
is
var temp = "This is a string."; var count = (temp.match(/is/g) || []).length; console.log(count);
そして、マッチしたものがなければ、0を返します。
0
var temp = "Hello World!"; var count = (temp.match(/is/g) || []).length; console.log(count);
function countInstances(string, word) { return string.split(word).length - 1; }
このような関数を定義するには、matchを使用します。
match
String.prototype.count = function(search) { var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g")); return m ? m.length:0; }
正規表現の
g
(globalの略)は、最初に出てくるものだけを探すのではなく、文字列全体を検索することを意味します。これはis
に2回マッチします。そして、マッチしたものがなければ、
0
を返します。このような関数を定義するには、
match
を使用します。