JavaScripti programm, et kontrollida, kas string algab mõne muu stringiga

Selles näites õpid kirjutama JavaScripti programmi, mis kontrollib, kas string algab mõne muu stringiga.

Selle näite mõistmiseks peaksid teil olema teadmised järgmistest JavaScripti programmeerimise teemadest:

  • JavaScripti string
  • Javascripti string algab funktsiooniga ()
  • JavaScripti string lastIndexOf ()
  • JavaScripti regex

Näide 1: startWith () kasutamine

 // 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äljund

 Nöör algab tähega "ta".

Ülalolevas programmis kasutatakse startsWith()meetodit , et teha kindlaks, kas string algab tähega 'he' . startsWith()Meetod kontrollib, kas string algab konkreetse string.

if… elseAvaldus kasutatakse seisundi kontrollimiseks.

Näide 2: lastIndexOf () kasutamine

 // 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äljund

 Nöör algab tähega "ta".

Ülalolevas programmis kasutatakse lastIndexOf()meetodit kontrollimaks, kas string algab mõne muu stringiga.

lastIndexOf()Meetod tagastab indeks otsitava stringi (siin otsivad esimesest indeks).

Näide 3: RegExi kasutamine

 // 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äljund

 Nöör algab tähega "ta".

Ülaltoodud programmis kontrollitakse stringi RegExi mustri ja test()meetodi abil.

/^ tähistab stringi algust.

Huvitavad Artiklid...