Created
November 10, 2010 16:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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