La méthode JavaScript String charAt () renvoie le caractère à l'index spécifié dans une chaîne.
La syntaxe de la charAt()
méthode est:
str.charAt(index)
Ici, str est une chaîne.
Paramètres charAt ()
La charAt()
méthode prend en compte:
- index - Un entier compris entre 0 et str.length - 1 . Si l'index ne peut pas être converti en entier ou n'est pas fourni, la valeur par défaut 0 est utilisée.
Valeur renvoyée par charAt ()
- Renvoie une chaîne représentant le caractère (exactement une unité de code UTF-16) à l'index spécifié.
Remarque : charAt()
renvoie une chaîne vide si l'index est hors plage.
Exemple: Utilisation de la méthode charAt ()
let sentence = "Happy Birthday to you!"; let index1 = sentence.charAt(2); console.log("Character at index 2:" + index1); // 'p' // index is converted to integer let index2 = sentence.charAt(6.5); // 'B' console.log("Character at index 6:" + index2); // Empty string if index out of range let index3 = sentence.charAt(100); console.log("Character at index 100:" + index3); // '' // default value is 0 let index4 = sentence.charAt(); console.log("Character at index 0:" + index4); // 'H'
Production
Caractère à l'index 2: p Caractère à l'index 6: B Caractère à l'index 100: Caractère à l'index 0: H
Lecture recommandée: JavaScript String charCodeAt ()