Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript 用于检查字符串中某个字符出现次数的程序

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

在本例中,您将学习编写一个 JavaScript 程序来检查字符串中某个字符的出现次数。
要理解此示例,您应该了解以下JavaScript 编程主题:
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() 方法返回指定索引处的字符。 在每次迭代期间,如果该索引处的字符与需要匹配的字符匹配,则计数变量增加 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 属性给出数组元素的长度。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4