Dalam contoh ini, Anda akan belajar menulis program JavaScript yang menghitung jumlah vokal dalam sebuah string.
Untuk memahami contoh ini, Anda harus memiliki pengetahuan tentang topik pemrograman JavaScript berikut:
- String JavaScript
- Pencocokan String Javascript ()
- String Javascript termasuk ()
Lima huruf a, e, i, o dan u disebut vokal. Semua huruf lain kecuali 5 huruf vokal ini disebut konsonan.
Contoh 1: Hitung Jumlah Vokal Menggunakan Regex
// program to count the number of vowels in a string function countVowel(str) ( // find the count of vowels const count = str.match(/(aeiou)/gi).length; // return number of vowels return count; ) // take input const string = prompt('Enter a string: '); const result = countVowel(string); console.log(result);
Keluaran
Masukkan string: Program JavaScript 5
Dalam program di atas, pengguna diminta untuk memasukkan string dan string itu diteruskan ke countVowel()
fungsi.
- Pola ekspresi reguler (RegEx) digunakan dengan
match()
metode untuk menemukan jumlah vokal dalam sebuah string. - Pola tersebut
/(aeiou)/gi
memeriksa semua vokal (case-insensitive) dalam sebuah string. Di sini,str.match(/(aeiou)/gi);
memberi ("a", "a", "i", "o", "a") - The
length
properti memberikan jumlah vokal hadir.
Contoh 2: Hitung Jumlah Vokal yang Digunakan untuk Loop
// program to count the number of vowels in a string // defining vowels const vowels = ("a", "e", "i", "o", "u") function countVowel(str) ( // initialize count let count = 0; // loop through string to test if each character is a vowel for (let letter of str.toLowerCase()) ( if (vowels.includes(letter)) ( count++; ) ) // return number of vowels return count ) // take input const string = prompt('Enter a string: '); const result = countVowel(string); console.log(result);
Keluaran
Masukkan string: Program JavaScript 5
Dalam contoh di atas,
- Semua vokal disimpan dalam
vowels
larik. - Awalnya, nilai
count
variabelnya adalah 0 . - The
for… of
Loop digunakan untuk iterate atas semua karakter dari string. - The
toLowerCase()
Metode bertobat semua karakter dari string ke huruf kecil. - The
includes()
Metode memeriksa apakahvowel
array berisi salah satu karakter dari string. - Jika ada karakter yang cocok, nilainya
count
dinaikkan 1 .