* Count occurrences of a substring in a string. * @param str The string to search in * @param substr The substring to count * @returns Number of non-overlapping occurrences
(str: string, substr: string)
| 31 | * @returns Number of non-overlapping occurrences |
| 32 | */ |
| 33 | function countOccurrences(str: string, substr: string): number { |
| 34 | if (substr === "") return 0 |
| 35 | let count = 0 |
| 36 | let pos = str.indexOf(substr) |
| 37 | while (pos !== -1) { |
| 38 | count++ |
| 39 | pos = str.indexOf(substr, pos + substr.length) |
| 40 | } |
| 41 | return count |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * Safely replace all occurrences of a literal string, handling $ escape sequences. |