Questa traduzione è incompleta. Collabora alla traduzione di questo articolo dall’originale in lingua inglese.
Il metodo indexOf() restituisce l'indice all'interno dell'oggetto String chiamante della prima occorrenza del valore specificato, avviando il cerca su fromIndex. Restituisce -1 se il valore non viene trovato.
La fonte per questo esempio interattivo è memorizzata in un repository GitHub. Se desideri contribuire al progetto di esempi interattivi, clona https://github.com/mdn/interactive-examples e inviaci una richiesta di pull.
Note: Per il metodo Array, vedere Array.prototype.indexOf().Sintassi
str.indexOf(searchValue[, fromIndex])
Parameteri
searchValue- Una stringa che rappresenta il valore da cercare.
fromIndexOptional- Un numero intero che rappresenta l'indice dal quale avviare la ricerca; il valore predefinito è
0. Per i valorifromIndexinferiori a 0 o maggiori distr.length, la ricerca inizia rispettivamente a index0ostr.length.
Valore di Ritorno
L'indice della prima occorrenza di searchValue o -1 se non nessuna occorrenza viene trovata.
Se viene specificata una stringa vuota come valore di searchValue, l'indice restituito da questa funzione sarà uguale a fromIndex (quindi verrà restituito 0 se fromIndex non è specificato).
Descrizione
I caratteri in una stringa sono indicizzati da sinistra a destra. L'indice del primo carattere è 0 e l'indice dell'ultimo carattere di una stringa chiamato stringName è stringName.length - 1.
'Blue Whale'.indexOf('Blue'); // returns 0
'Blue Whale'.indexOf('Blute'); // returns -1
'Blue Whale'.indexOf('Whale', 0); // returns 5
'Blue Whale'.indexOf('Whale', 5); // returns 5
'Blue Whale'.indexOf('Whale', 7); // returns -1
'Blue Whale'.indexOf(''); // returns 0
'Blue Whale'.indexOf('', 9); // returns 9
'Blue Whale'.indexOf('', 10); // returns 10
'Blue Whale'.indexOf('', 11); // returns 10
Il metodo indexOf() è case sensitive. Ad esempio, la seguente espressione restituisce -1:
'Blue Whale'.indexOf('blue'); // returns -1
Controllare le occorrenze
In JavaScript, 0 non corrisponde al valore booleano true e -1 non corrisponde al valore booleano false. Pertanto per controllare se una stringa è contenuta all'interno di un altra, il codice corretto è:
'Blue Whale'.indexOf('Blue') !== -1; // true, "Blue" è contenuta all'interno di "Blue Whale"
'Blue Whale'.indexOf('Bloe') !== -1; // false, "Bloe" non è contenuta all'interno di "Blue Whale"
Esempi
Usando indexOf()
Nell'esempio seguente viene utilizzato indexOf() per individuare i valori nella stringa "Brave new world".
var str = 'Brave new world';
console.log('Index of first w from start is ' + str.indexOf('w')); // logs 8
console.log('Index of "new" from start is ' + str.indexOf('new')); // logs 6
indexOf() e case-sensitivity
The following example defines two string variables. The variables contain the same string except that the second string contains uppercase letters. The first console.log() method displays 19. But because the indexOf() method is case sensitive, the string "cheddar" is not found in myCapString, so the second console.log() method displays -1.
var myString = 'brie, pepper jack, cheddar';
var myCapString = 'Brie, Pepper Jack, Cheddar';
console.log('myString.indexOf("cheddar") is ' + myString.indexOf('cheddar'));
// logs 19
console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf('cheddar'));
// logs -1
Using indexOf() to count occurrences of a letter in a string
The following example sets count to the number of occurrences of the letter e in the string str:
var str = 'To be, or not to be, that is the question.';
var count = 0;
var pos = str.indexOf('e');
while (pos !== -1) {
count++;
pos = str.indexOf('e', pos + 1);
}
console.log(count); // displays 4
Specifications
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. |
| ECMAScript 5.1 (ECMA-262) The definition of 'String.prototype.indexOf' in that specification. |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'String.prototype.indexOf' in that specification. |
Standard | |
| ECMAScript Latest Draft (ECMA-262) The definition of 'String.prototype.indexOf' in that specification. |
Draft |
Browser compatibility
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Basic support | Chrome Full support Yes | Edge Full support Yes | Firefox Full support 1 | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Edge Mobile Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes | nodejs Full support Yes |
Legend
- Full support
- Full support