For anyone that finds this thread in the future, note that the accepted answer will not always return the correct value if you generalize it, since it will choke on regex operators like $
and .
. Here's a better version, that can handle any needle:
function occurrences (haystack, needle) { var _needle = needle .replace(/\[/g, '\\[') .replace(/\]/g, '\\]') return ( haystack.match(new RegExp('['+ _needle +']', 'g')) || [] ).length}