Lima huruf a, e, saya, o dan u disebut vokal. Semua huruf lainnya kecuali ini 5 vokal 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
Enter a string: JavaScript program 5
Dalam program di atas, pengguna diminta untuk memasukkan string dan string itu diteruskan ke countVowel()
fungsi.
- Pola regular expression (RegEx) digunakan dengan
match()
metode untuk menemukan jumlah vokal dalam sebuah string. - Pola
/[aeiou]/gi
memeriksa semua vokal (case-insensitive) dalam sebuah string. Sini,str.match(/[aeiou]/gi);
memberi [“a”, “a”, “i”, “o”, “a”] - Itu
length
properti memberikan jumlah vokal yang ada.
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
Enter a string: JavaScript program 5
Dalam contoh di atas,
- Semua vokal disimpan dalam a
vowels
Himpunan. - Awalnya, nilai file
count
variabel adalah 0. - Itu
for...of
loop digunakan untuk mengulang semua karakter string. - Itu
toLowerCase()
metode mengubah semua karakter string menjadi huruf kecil. - Itu
includes()
metode memeriksa apakahvowel
array berisi salah satu karakter string. - Jika ada karakter yang cocok, nilai
count
meningkat sebesar 1.