1 | ;
|
2 |
|
3 | /**
|
4 | * Based on https://github.com/helpers/handlebars-helpers/blob/0.8.4/lib/string.js#L221-L233
|
5 | *
|
6 | * Return the number of occurrences of `substring` within the
|
7 | * given `string`.
|
8 | *
|
9 | * ```handlebars
|
10 | * {{occurrences "foo bar foo bar baz" "foo"}}
|
11 | * //=> 2
|
12 | * ```
|
13 | * @param {String} `str`
|
14 | * @param {String} `substring`
|
15 | * @return {Number} Number of occurrences
|
16 | */
|
17 | function helper(paper) {
|
18 | paper.handlebars.registerHelper('occurrences', function(str, substring) {
|
19 | if (typeof str !== 'string' || str.length === 0) {
|
20 | return 0;
|
21 | }
|
22 |
|
23 | if (typeof substring !== 'string' || substring.length === 0) {
|
24 | return 0;
|
25 | }
|
26 |
|
27 | const len = substring.length;
|
28 | let pos = 0;
|
29 | let numOccurrences = 0;
|
30 |
|
31 | while ((pos = str.indexOf(substring, pos)) > -1) {
|
32 | pos += len;
|
33 | numOccurrences++;
|
34 | }
|
35 |
|
36 | return numOccurrences;
|
37 | });
|
38 | }
|
39 |
|
40 | module.exports = helper;
|