JavaScript 程序:检查字符串中字符出现的次数

要理解此示例,您应了解以下 JavaScript 编程 主题


如果检查字符串“school”中字符“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

在上面的示例中,会提示用户输入一个字符串和要检查的字符。

  • 开始时,count 变量的值为 0
  • 使用 for 循环遍历字符串。
  • charAt() 方法返回指定索引处的字符。
  • 在每次迭代中,如果该索引处的字符与要匹配的字符匹配,则 count 变量会增加 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 属性给出数组元素的长度。

在我们结束之前,让我们用 JavaScript 程序来检验你对“检查字符串中字符出现次数”的知识吧!你能解决下面的挑战吗?

挑战

编写一个函数来查找字符串中字符的出现次数。

  • 返回 chstr 中出现的次数。
  • 例如,如果给出 str = "programming"ch = 'm',则 'm' 在 str 中出现的次数是 2
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战