2021-06-15 00:49:18 -07:00
---
id: 596fda99c69f779975a1b67d
2022-02-04 00:46:32 +05:30
title: Contare le occorrenze di una sottostringa
2021-06-15 00:49:18 -07:00
challengeType: 5
forumTopicId: 302237
dashedName: count-occurrences-of-a-substring
---
# --description--
2022-02-04 00:46:32 +05:30
Crea una funzione, o mostra una funzione integrata, per contare il numero di occorrenze non sovrapposte di una sottostringa all'interno di una stringa.
2021-06-15 00:49:18 -07:00
2022-02-04 00:46:32 +05:30
La funzione dovrebbe prendere due argomenti:
2021-06-15 00:49:18 -07:00
< ul >
2022-02-04 00:46:32 +05:30
< li > il primo argomento è la stringa da esaminare, e< / li >
< li > il secondo la sotto-stringa da trovare.< / li >
2021-06-15 00:49:18 -07:00
< / ul >
2022-02-04 00:46:32 +05:30
Dovrebbe restituire un numero intero.
2021-06-15 00:49:18 -07:00
2022-02-04 00:46:32 +05:30
La ricerca dovrebbe produrre il maggior numero di sottostringhe non sovrapposte.
2021-06-15 00:49:18 -07:00
2022-02-04 00:46:32 +05:30
In generale, questo significa essenzialmente cercare da sinistra a destra o da destra a sinistra.
2021-06-15 00:49:18 -07:00
# --hints--
2022-02-04 00:46:32 +05:30
`countSubstring` dovrebbe essere una funzione.
2021-06-15 00:49:18 -07:00
```js
assert(typeof countSubstring === 'function');
```
2022-02-04 00:46:32 +05:30
`countSubstring("the three truths", "th")` dovrebbe restituire `3` .
2021-06-15 00:49:18 -07:00
```js
assert.equal(countSubstring(testCases[0], searchString[0]), results[0]);
```
2022-02-04 00:46:32 +05:30
`countSubstring("ababababab", "abab")` dovrebbe restituire `2` .
2021-06-15 00:49:18 -07:00
```js
assert.equal(countSubstring(testCases[1], searchString[1]), results[1]);
```
2022-02-04 00:46:32 +05:30
`countSubstring("abaabba*bbaba*bbab", "a*b")` dovrebbe restituire `2` .
2021-06-15 00:49:18 -07:00
```js
assert.equal(countSubstring(testCases[2], searchString[2]), results[2]);
```
# --seed--
## --after-user-code--
```js
const testCases = ['the three truths', 'ababababab', 'abaabba*bbaba*bbab'];
const searchString = ['th', 'abab', 'a*b'];
const results = [3, 2, 2];
```
## --seed-contents--
```js
function countSubstring(str, subStr) {
return true;
}
```
# --solutions--
```js
function countSubstring(str, subStr) {
const escapedSubStr = subStr.replace(/[.+*?^$[\]{}()|/]/g, '\\$&');
const matches = str.match(new RegExp(escapedSubStr, 'g'));
return matches ? matches.length : 0;
}
```