You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
programming-examples/js/String/Count the occurrence of a s...

16 lines
501 B
JavaScript

function count(main_str, sub_str)
{
main_str += '';
sub_str += '';
if (sub_str.length <= 0)
{
return main_str.length + 1;
}
subStr = sub_str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return (main_str.match(new RegExp(subStr, 'gi')) || []).length;
}
console.log(count("The quick brown fox jumps over the lazy dog", 'the'));
console.log(count("The quick brown fox jumps over the lazy dog", 'fox',false));