Šiame pavyzdyje išmoksite rašyti „JavaScript“ programą, kuri patikrins, ar eilutė prasideda kita eilute.
Norėdami suprasti šį pavyzdį, turite žinoti šias „JavaScript“ programavimo temas:
- „JavaScript“ eilutė
- „Javascript“ eilutė prasideda su ()
- „JavaScript“ eilutė lastIndexOf ()
- „JavaScript Regex“
1 pavyzdys: naudojimas 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".`); )
Rezultatas
Stygos prasideda „jis“.
Ankstesnėje programoje startsWith()
metodas naudojamas nustatyti, ar eilutė prasideda „jis“ . Į startsWith()
metodas patikrina, ar eilutė prasideda ypač eilutę.
if… else
Pareiškimas yra naudojama patikrinti būklę.
2 pavyzdys: lastIndexOf () naudojimas
// 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".`); )
Rezultatas
Stygos prasideda „jis“.
Ankstesnėje programoje lastIndexOf()
metodas naudojamas patikrinti, ar eilutė prasideda kita eilute.
lastIndexOf()
Metodas grąžina ieškoma eilutę (čia ieško iš pirmojo indeksą) indeksą.
3 pavyzdys: „RegEx“ naudojimas
// 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".`); )
Rezultatas
Stygos prasideda „jis“.
Pirmiau pateiktoje programoje eilutė tikrinama naudojant „RegEx“ modelį ir test()
metodą.
/^
nurodo eilutės pradžią.