文字列内の文字の出現回数をチェックするJavaScriptプログラム

Javascript

‘の発生数を確認するとo ‘ 文字列内 ‘学校’、結果は 2

例1:forループを使用して文字の出現を確認する

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

出力

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

上記の例では、ユーザーはチェックする文字列と文字を入力するように求められます。

  • 最初は、カウント変数の値は次のとおりです。 0
  • ザ・ for ループは、文字列を反復処理するために使用されます。
  • ザ・ charAt() メソッドは、指定されたインデックスの文字を返します。
  • 各反復中に、そのインデックスの文字が一致する必要のある文字と一致する場合、カウント変数は次のように増加します。 1

例2:正規表現を使用して文字の出現を確認する

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

出力

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

上記の例では、正規表現(regex)を使用して文字列の出現を検索しています。

  • const re = new RegExp(letter, 'g'); 正規表現を作成します。
  • ザ・ match() メソッドは、すべての一致を含む配列を返します。 ここに、 str.match(re);与える [“o”, “o”]
  • ザ・ length プロパティは、配列要素の長さを示します。



Hope this helps!

Source link

コメントを残す

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