Šajā piemērā jūs iemācīsities rakstīt JavaScript programmu, kas pārbauda rakstzīmes virknes virknes gadījumu skaitu.
Lai saprastu šo piemēru, jums jāpārzina šādas JavaScript programmēšanas tēmas:
- JavaScript virkne
- JavaScript regex
Ja pārbaudāt virknes “ skola” “ o” gadījumu skaitu, rezultāts ir 2 .
1. piemērs: pārbaudiet rakstzīmju parādīšanos, izmantojot cilpu
// program to check the number of occurrence of a character function countString(str, letter) ( let count = 0; // looping through the items for (let i = 0; i < str.length; i++) ( // check if the character is at that position if (str.charAt(i) == letter) ( count += 1; ) ) return count; ) // take input from the user const string = prompt('Enter a string: '); const letterToCheck = prompt('Enter a letter to check: '); //passing parameters and calling the function const result = countString(string, letterToCheck); // displaying the result console.log(result);
Rezultāts
Ievadiet virkni: skola Ievadiet burtu, lai pārbaudītu: o 2
Iepriekš minētajā piemērā lietotājam tiek piedāvāts ievadīt virkni un pārbaudāmo rakstzīmi.
- Sākumā skaitāmā mainīgā vērtība ir 0 .
for
Cilpa tiek izmantota, lai atkārtot pār stīgām.charAt()
Metode atgriež rakstzīmi norādīto indeksu.- Katras iterācijas laikā, ja raksturs šajā indeksā atbilst vajadzīgajam rakstzīmei, lai tas atbilstu, skaitītāja mainīgais tiek palielināts par 1 .
2. piemērs. Pārbaudiet rakstzīmes sastopamību, izmantojot Regex
// program to check the occurrence of a character function countString(str, letter) ( // creating regex const re = new RegExp(letter, 'g'); // matching the pattern const count = str.match(re).length; return count; ) // take input from the user const string = prompt('Enter a string: '); const letterToCheck = prompt('Enter a letter to check: '); //passing parameters and calling the function const result = countString(string, letterToCheck); // displaying the result console.log(result);
Rezultāts
Ievadiet virkni: skola Ievadiet burtu, lai pārbaudītu: o 2
Iepriekš minētajā piemērā, lai atrastu virknes parādīšanos, tiek izmantota regulārā izteiksme (regex).
const re = new RegExp(letter, 'g');
rada regulāru izteiksmi.match()
Metode atgriež masīvu, kas satur visus sērkociņi. Lūk,str.match(re);
dod ("o", "o").length
Īpašums dod garumu masīva elements.