How to count the number of non-overlapping instances of substring in a string in Node.js

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 str = "node.js php c++ python php phphp php";
 
console.log(countNonOverlappingOccurrences(str, "php"));
 
 
    
/*
run:
    
4
 
*/

 



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 str = "node.js php c++ python php phphp php";
 
console.log(countNonOverlappingOccurrences(str, "php"));
 
 
    
/*
run:
    
4
 
*/

 



answered Aug 24, 2024 by avibootz
...