jQuery String in String Counting

Sam Deering
Share

How to count the number of occurences of a string (subset of characters/regular expression/wildcards) inside another string.

Method 1 – Using a Regular Expression Match

var emails = 'sam@jquery4u.com,admin@jquery4u.com,someone@jquery4u.com',
    count = emails.match(/@/igm).length;
console.log(count);
//output: 3

Word of warning that using .length function on a regular expression which has no matches will result in a null error.

TypeErroremailsmatch

var emails = '',
    count = emails.match(/@/igm).length;
console.log(count);
//output: TypeError: emails.match(/@/gim) is null

If you check the count is not null before assigning the value it does not error and will give you 0 for a no count.

Working Version (null proof):

var emails = 'sam@jquery4u.com,admin@jquery4u.com,someone@jquery4u.com',
    regex = /@/igm,
    count = emails.match(regex),
    count = (count) ? count.length : 0;

console.log(count);
//output: 3

Method 2 – Using a indexOf() Pos Function

function occurrences(string, substring){
    var n=0;
    var pos=0;

    while(true){
        pos=string.indexOf(substring,pos);
        if(pos!=-1){ n++; pos+=substring.length;}
        else{break;}
    }
    return(n);
}
count= occurrences(emails,'@');
console.log(count);
//output: 3