indexOf() Trovare una stringa in una stringa




Trovare una stringa in una stringa
Il indexOf()metodo restituisce l'indice (della posizione) firstdell'occorrenza di un testo specificato in una stringa:

Esempio
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The indexOf() method returns the position of the first occurrence of a specified text:</p>

<p id="demo"></p>

<script>
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
document.getElementById("demo").innerHTML = pos;
</script>

</body>
</html>

Entrambi indexOf()e lastIndexOf()restituiscono -1 se il testo non viene trovato.
Esempio
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("John");

Entrambi i metodi accettano un secondo parametro come posizione iniziale per la ricerca:

Esempio
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate", 15);










( indexoftrovareunastringainunastringa.html )- by Paolo Puglisi - Modifica del 17/12/2023