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

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

$
0
0

Here is my solution, in 2022, using map() and filter() :

string = "Xanthous: A person with yellow hair. Her hair was very xanthous in colour."       count = string.split('').map((e,i) => { if(e === 'e') return i;}).filter(Boolean).length

Just for the fun of using these functions. The example counts the number of "e" in my string.

This is the same as using the match() function :

(string.match(/e/g)||[]).length

or simply the split() function:

string.split('e').length - 1

I think the best is to use match(), because it consumes less resources! My answer is just for fun and to show that there are many possibilities to solve this problem


Viewing all articles
Browse latest Browse all 43

Trending Articles



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