JavaScript-programma om te controleren of een string begint met een andere string

In dit voorbeeld leert u een JavaScript-programma te schrijven dat controleert of een string begint met een andere string.

Om dit voorbeeld te begrijpen, moet u kennis hebben van de volgende JavaScript-programmeeronderwerpen:

  • JavaScript-tekenreeks
  • Javascript String startsWith ()
  • JavaScript-tekenreeks lastIndexOf ()
  • JavaScript Regex

Voorbeeld 1: startsWith () gebruiken

 // 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".`); )

Uitvoer

 De string begint met "hij".

In het bovenstaande programma wordt de startsWith()methode gebruikt om te bepalen of de string begint met 'hij' . De startsWith()methode controleert of de string begint met de betreffende string.

Het if… elsestatement wordt gebruikt om de conditie te controleren.

Voorbeeld 2: lastIndexOf () gebruiken

 // 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".`); )

Uitvoer

 De string begint met "hij".

In het bovenstaande programma wordt de lastIndexOf()methode gebruikt om te controleren of een string begint met een andere string.

De lastIndexOf()methode retourneert de index van de gezochte string (hier zoeken vanaf de eerste index).

Voorbeeld 3: RegEx gebruiken

 // 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".`); )

Uitvoer

 De string begint met "hij".

In het bovenstaande programma wordt de string gecontroleerd met behulp van het RegEx-patroon en de test()methode.

/^ geeft het begin van de string aan.

Interessante artikelen...