Skip to content

Commit 83f146e

Browse files
committed
Add a recipe to count occurrences of a given string within a message
1 parent 2fd9c30 commit 83f146e

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

chapters/strings/finding-substrings.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,18 @@ message.indexOf "This", 5
2424
message.lastIndexOf "This"
2525
# => 49
2626

27+
28+
# Count occurrences of a given string
29+
30+
substrCount = (str, subStr) ->
31+
32+
re = new RegExp( subStr ,"g" )
33+
34+
( str.match(re) or [] ).length
35+
36+
substrCount message, " a "
37+
# => 3
38+
2739
{% endhighlight %}
2840

2941
## Discussion

0 commit comments

Comments
 (0)