Function count the occurrences of substring in a string; - Node.js String

Node.js examples for String:sub string

Description

Function count the occurrences of substring in a string;

Demo Code

/**//w  w  w .j av a2 s . c o  m
 * Function count the occurrences of substring in a string;
 * @param {String} subString    Required. The string to search for;
 */
String.prototype.occurrences = function(subString){

    subString+="";
    if(subString.length<=0) return this.length+1;

    var n=0, pos=0;

    while(true){
        pos=this.indexOf(subString,pos);
        if(pos>=0){ n++; pos+=subString.length; } else break;
    }
    return(n);
};

Related Tutorials