Quantcast
Channel: How to count string occurrence in string? - Stack Overflow
Viewing all articles
Browse latest Browse all 43

Answer by bcherny for How to count string occurrence in string?

$
0
0

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}

Viewing all articles
Browse latest Browse all 43

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>