This code only instantiates one RegExp object and uses a reverse while-loop. I'm pretty sure this is as fast as you can go without breaking the laws of physics :)
This is whats happening:
- Construct regular expression string using a reverse while-loop
- New up just one RegExp object, and
match() it on the string - Count the length of the array returned by the
match() function
Here's the implementation:
var countries = ["Afganistan", "America", "Island"]; var sentence = "I love Afganistan, America.. And I love America some more"; function countOccurrences(a, s) { var re = "", l = a.length, m; while (l) { l--; re += a[l]; if (l > 0) re += "|"; } m = s.match(new RegExp(re, "gi")) || []; return m.length; }
Note: I am of course expecting the entries in the array to be sanitized for any special characters that will break the regular expression constructed within the function.
var occurrences = function countOccurrences(countries, sentence); // returns 3