Dans cet exemple, vous apprendrez à écrire un programme JavaScript qui vérifiera si une chaîne commence par une autre chaîne.
Pour comprendre cet exemple, vous devez avoir la connaissance des sujets de programmation JavaScript suivants:
- Chaîne JavaScript
 - La chaîne Javascript commence avec ()
 - Chaîne JavaScript lastIndexOf ()
 - JavaScript Regex
 
Exemple 1: Utilisation de startsWith ()
 // program to check if a string starts with another string const string = 'hello world'; const toCheckString = 'he'; if(string.startsWith(toCheckString)) ( console.warn('The string starts with "he".'); ) else ( console.warn(`The string does not starts with "he".`); )
Production
La chaîne commence par "il".
Dans le programme ci-dessus, la startsWith()méthode est utilisée pour déterminer si la chaîne commence par «he» . La startsWith()méthode vérifie si la chaîne commence par la chaîne particulière.
L' if… elseinstruction est utilisée pour vérifier la condition.
Exemple 2: Utilisation de lastIndexOf ()
 // program to check if a string starts with another string const string = 'hello world'; const toCheckString = 'he'; let result = string.lastIndexOf(toCheckString, 0) === 0; if(result) ( console.warn('The string starts with "he".'); ) else ( console.warn(`The string does not starts with "he".`); )
Production
La chaîne commence par "il".
Dans le programme ci-dessus, la lastIndexOf()méthode est utilisée pour vérifier si une chaîne commence par une autre chaîne.
La lastIndexOf()méthode renvoie l'index de la chaîne recherchée (ici à partir du premier index).
Exemple 3: Utilisation de RegEx
 // program to check if a string starts with another string const string = 'hello world'; const pattern = /^he/; let result = pattern.test(string); if(result) ( console.warn('The string starts with "he".'); ) else ( console.warn(`The string does not starts with "he".`); )
Production
La chaîne commence par "il".
Dans le programme ci-dessus, la chaîne est vérifiée à l'aide du modèle RegEx et de la test()méthode.
/^ indique le début de la chaîne.








