V tem primeru se boste naučili pisati program JavaScript, da preverite, ali se niz začne in konča z določenimi znaki.
Če želite razumeti ta primer, morate poznati naslednje teme programiranja JavaScript:
- Niz JavaScript
- Javascript String se začne z ()
- Javascript niz se konča z ()
- Regex JavaScript
Primer 1: Preverite niz z uporabo vgrajenih metod
// program to check if a string starts with 'S' and ends with 'G' function checkString(str) ( // check if the string starts with S and ends with G if(str.startsWith('S') && str.endsWith('G')) ( console.log('The string starts with S and ends with G'); ) else if(str.startsWith('S')) ( console.log('The string starts with S but does not end with G'); ) else if(str.endsWith('G')) ( console.log('The string starts does not with S but end with G'); ) else ( console.log('The string does not start with S and does not end with G'); ) ) // take input let string = prompt('Enter a string: '); checkString(string);
Izhod
Vnesite niz: niz Niz se začne s S, vendar se ne konča z G
V zgornjem programu sta uporabljeni obe metodi startsWith()
in endsWith()
.
- V
startsWith()
samem metoda če niz začne s posebno vrvico. - V
endsWith()
samem metodo, če niz konča s posebnim vrvico.
Zgornji program ne preverja malih črk. Zato sta G in g različni.
Prav tako lahko preverite, ali se zgornji znak začne s S ali s in konča z G ali g .
str.startsWith('S') || str.startsWith('s') && str.endsWith('G') || str.endsWith('g');
2. primer: Preverite niz z uporabo regularnega izraza
// program to check if a string starts with 'S' and ends with 'G' function checkString(str) ( // check if the string starts with S and ends with G if( /^S/i.test(str) && /G$/i.test(str)) ( console.log('The string starts with S and ends with G'); ) else if(/^S/i.test(str)) ( console.log('The string starts with S but does not ends with G'); ) else if(/G$/i.test(str)) ( console.log('The string starts does not with S but ends with G'); ) else ( console.log('The string does not start with S and does not end with G'); ) ) // for loop to show different scenario for (let i = 0; i < 3; i++) ( // take input const string = prompt('Enter a string: '); checkString(string); )
Izhod
Vnesite niz: niz Niz se začne s S in konča z G Vnesite niz: niz Niz se začne s S in konča z G Vnesite niz: JavaScript Niz se ne začne s S in se ne konča z G
V zgornjem programu, je regularni izraz (regularni izraz) se uporablja z test()
metodo, da preveri, če je niz začne z S in konča z G .
- V
/^S/i
samem vzorec, če je niz je S ali s . Tui
pomeni, da niz ne razlikuje med velikimi in malimi črkami. Zato se S in s štejeta za isti. - V
/G$/i
vzorci preveri, ali je niz je G ali g . if… else… if
Izjava se uporablja za preverjanje stanja in ustrezno prikazati rezultate.for
Zanka se uporablja, da bi različne vhode od uporabnika, da kažejo različne primere.