Absolutely: You can use String#matchto do this:
var count = "This is a test text".match(/te/g).length;
/te/g ( "" , ) . - .
, , , . :
function countMatches(str, re) {
var counter;
counter = 0;
while (re.test(str)) {
++counter;
}
return counter;
}
var count = countMatches("This is a test text", /te/g);
RegExp#test . ( kennebec , , RegExp#exec !) , , , , , String#match , , () β , , .
, , , :
function countMatches(str, substr) {
var index, counter, sublength;
sublength = substr.length;
counter = 0;
for (index = str.indexOf(substr);
index >= 0;
index = str.indexOf(substr, index + sublength))
{
++counter;
}
return counter;
}
var count = countMatches("This is a test text", "te");
, RegExp, .