Skip to content

Commit 202bdfd

Browse files
Data-Meistersukima
authored andcommitted
Add a recipe to count occurrences of a given string within a message
1 parent 2fd9c30 commit 202bdfd

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

chapters/strings/finding-substrings.md

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,14 @@ message.indexOf "This", 5
2424
message.lastIndexOf "This"
2525
# => 49
2626

27-
{% endhighlight %}
2827

29-
## Discussion
28+
# Count occurrences of a given string
29+
30+
substrCount = (str, subStr) ->
31+
re = new RegExp( subStr ,"g" )
32+
( str.match(re) or [] ).length
3033

31-
Still need recipe to count occurrences of a given string within a message.
34+
substrCount message, " a "
35+
# => 3
36+
37+
{% endhighlight %}

0 commit comments

Comments
 (0)