How to count the number of non-overlapping instances of substring in a string in JavaScript

2 Answers

0 votes
function countNonOverlappingOccurrences(str, substr) {
    if (substr === "") return 0;

    let count = 0;
    let offset = str.indexOf(substr);

    while (offset !== -1) {
        count++;
        offset = str.indexOf(substr, offset + substr.length);
    }

    return count;
}

const s = "javascript php c++ python php phphp";

console.log(countNonOverlappingOccurrences(s, "php"));


   
/*
run:
   
3

*/

 



answered Aug 24, 2024 by avibootz
0 votes
function countNonOverlappingOccurrences(str, substr) {
    return (str.length - str.replace(new RegExp(substr, "gi"), "").length) / substr.length;
}

const s = "javascript php c++ python php phphp";

console.log(countNonOverlappingOccurrences(s, "php"));


   
/*
run:
   
3

*/

 



answered Aug 24, 2024 by avibootz
...