Chaîne JavaScript indexOf()
Exemples
Rechercher une chaîne pour "bienvenue":
let text = "Hello world, welcome to the universe.";
let result = text.indexOf("welcome");
Rechercher une chaîne pour "Bienvenue":
let text = "Hello world, welcome to the universe.";
let result = text.indexOf("Welcome");
Trouvez la première occurrence de "e":
let text = "Hello world, welcome to the universe.";
text.indexOf("e");
Trouvez la première occurrence de "e", en commençant à la position 5 :
let text = "Hello world, welcome to the universe.";
text.indexOf("e", 5);
Trouvez la première occurrence de "a":
let text = "Hello world, welcome to the universe.";
text.indexOf("a");
Définition et utilisation
La indexOf()
méthode renvoie la position de la première occurrence d'une valeur dans une chaîne.
La indexOf()
méthode renvoie -1 si la valeur n'est pas trouvée.
La indexOf()
méthode est sensible à la casse.
Syntaxe
string.indexOf(searchvalue, start)
Paramètres
Parameter | Description |
searchvalue | Required. The string to search for. |
start | Optional. The position to start from (default is 0). |
Valeur de retour
Taper | La description |
Un numéro | La première position où la valeur de recherche se produit. -1 si cela ne se produit jamais. |
La différence entre
String indexOf() et String search()
La indexOf()
méthode ne peut pas rechercher une expression régulière.
Le search()
ne peut pas accepter d'argument de position de départ.
Prise en charge du navigateur
indexOf()
est une fonctionnalité ECMAScript1 (ES1).
ES1 (JavaScript 1997) est entièrement pris en charge dans tous les navigateurs :
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |