Skip to content

Instantly share code, notes, and snippets.

@getify
Created November 10, 2010 16:12
Show Gist options
  • Save getify/671048 to your computer and use it in GitHub Desktop.
Save getify/671048 to your computer and use it in GitHub Desktop.
using join() and regex to count occurrences of some string in an array
function count_str_occurrences(str,arr) {
var arr_str = arr.join(","),
regex = new RegExp("(?:^|,)"+str+"(?:,|$)","g"),
tmp;
if (tmp = arr_str.match(regex)) {
return tmp.length;
}
return 0;
}
count_str_occurrences("ab",["a", "ab", "a", "ac", "ca", "ba", "ab", "ad", "ab", "a", "ab"]); // 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment