// Use match instead 'a a a'.match(/(a)/g).length // outputs: 3
Here is what the above code is Doing:
1. The first line creates a regular expression object that matches the string “a”.
2. The second line creates a string object with the value “a a a”.
3. The third line calls the match method on the string object. The match method takes a regular expression as an argument.
4. The regular expression object created in step 1 is passed as an argument to the match method.
5. The match method returns an array containing the matches.
6. The length property of the array is accessed to get the number of matches.