文字列内の母音の数を数えるJavaScriptプログラム

Javascript

5文字 a、e、i、o そして u 母音と呼ばれます。 これらを除く他のすべてのアルファベット 5 母音は子音と呼ばれます。

例1:正規表現を使用して母音の数を数える

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

出力

Enter a string: JavaScript program
5

上記のプログラムでは、ユーザーは文字列を入力するように求められ、その文字列が countVowel() 関数。

  • 正規表現(RegEx)パターンは、 match() 文字列内の母音の数を見つけるメソッド。
  • パターン /[aeiou]/gi 文字列内のすべての母音(大文字と小文字を区別しない)をチェックします。 ここに、
    str.match(/[aeiou]/gi); 与える [“a”, “a”, “i”, “o”, “a”]
  • ザ・ length プロパティは、存在する母音の数を示します。

例2:forループを使用して母音の数を数える

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

出力

Enter a string: JavaScript program
5

上記の例では、

  • すべての母音はに保存されます vowels アレイ。
  • 最初に、の値 count 変数は 0
  • ザ・ for...of ループは、文字列のすべての文字を反復処理するために使用されます。
  • ザ・ toLowerCase() メソッドは、文字列のすべての文字を小文字に変換します。
  • ザ・ includes() メソッドは、 vowel 配列には、文字列の任意の文字が含まれます。
  • 一致する文字がある場合、 count によって増加します 1



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です