U ovom ćete primjeru naučiti napisati JavaScript program koji će provjeriti započinje li niz s drugim nizom.
Da biste razumjeli ovaj primjer, trebali biste imati znanje o sljedećim temama programiranja JavaScript:
- JavaScript niz
- Javascript niz počinje s ()
- JavaScript niz lastIndexOf ()
- JavaScript regularni izraz
Primjer 1: Korištenje 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".`); )
Izlaz
Niz počinje s "on".
U gore navedenom programu startsWith()
metoda se koristi za određivanje započinje li niz s 'he' . The startsWith()
metoda provjerava da li je niz počinje s određenom nizu.
if… else
Izjava se koristi za provjeru stanja.
Primjer 2: Korištenje 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".`); )
Izlaz
Niz počinje s "on".
U gore navedenom programu lastIndexOf()
metoda se koristi za provjeru započinje li niz s drugim nizom.
lastIndexOf()
Metoda vraća indeks traženom nizu (ovdje traži od prvog indeksa).
Primjer 3: Korištenje RegEx-a
// 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".`); )
Izlaz
Niz počinje s "on".
U gore navedenom programu niz se provjerava pomoću RegEx uzorka i test()
metode.
/^
označava početak niza.