Program JavaScript untuk Memeriksa Jumlah Kemunculan Karakter dalam String

0
(0)

Jika Anda memeriksa jumlah kemunculan ‘Hai’ dalam string ‘sekolah’, hasilnya adalah 2.

Contoh 1: Periksa Kemunculan Karakter yang Menggunakan for Loop

// 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);

Keluaran

Enter a string: school
Enter a  letter to check: o
2

Dalam contoh di atas, pengguna diminta untuk memasukkan string dan karakter yang akan diperiksa.

  • Pada awalnya, nilai variabel hitung adalah 0.
  • Itu for loop digunakan untuk mengulang string.
  • Itu charAt() metode mengembalikan karakter pada indeks tertentu.
  • Selama setiap iterasi, jika karakter pada indeks itu cocok dengan karakter yang diperlukan untuk dicocokkan, maka variabel hitungan dinaikkan 1.

Contoh 2: Periksa kemunculan karakter menggunakan 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);

Keluaran

Enter a string: school
Enter a  letter to check: o
2

Dalam contoh di atas, ekspresi reguler (regex) digunakan untuk mencari kemunculan string.

  • const re = new RegExp(letter, 'g'); membuat ekspresi reguler.
  • Itu match() metode mengembalikan array yang berisi semua kecocokan. Sini, str.match(re);memberi [“o”, “o”].
  • Itu length properti memberikan panjang elemen array.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.