JavaScript
Article

jQuery String in String Counting

By Sam Deering

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
  • oli

    You are the best!

    I was stuck on this issue! Your null proof version works like a charm

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.