V tomto príklade sa naučíte písať program JavaScript, ktorý skontroluje, či reťazec začína iným reťazcom.
Aby ste pochopili tento príklad, mali by ste mať znalosti nasledujúcich tém programovania v jazyku JavaScript:
- Reťazec JavaScript
- Reťazec Javascript sa začína na ()
- Reťazec JavaScriptu lastIndexOf ()
- JavaScriptový regulárny výraz
Príklad 1: Používanie startWith ()
// 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".`); )
Výkon
Reťazec začína na „on“.
Vo vyššie uvedenom programe sa startsWith()metóda používa na zistenie, či reťazec začína reťazcom „he“ . Tieto startsWith()metódy kontroluje, či reťazec začína s daným reťazcom.
if… elseVyhlásenie sa používa ku kontrole stavu.
Príklad 2: Použitie 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".`); )
Výkon
Reťazec začína na „on“.
Vo vyššie uvedenom programe sa lastIndexOf()metóda používa na kontrolu, či reťazec začína iným reťazcom.
lastIndexOf()Metóda vracia index hľadaného reťazca (tu hľadá od prvého indexu).
Príklad 3: Používanie 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".`); )
Výkon
Reťazec začína na „on“.
Vo vyššie uvedenom programe sa reťazec kontroluje pomocou vzoru RegEx a test()metódy.
/^ označuje začiatok reťazca.








