"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to count the number of characters occurrences and verify the length of string in JavaScript?

How to count the number of characters occurrences and verify the length of string in JavaScript?

Posted on 2025-04-14
Browse:894

How Can I Count Character Occurrences and Validate String Lengths in JavaScript?

Counting Character Occurrences and Validating String Lengths in Javascript

In Javascript, determining the frequency of a character within a string is a common task. To count the occurrences, a straightforward method exists:

Consider the following string:

var mainStr = "str1,str2,str3,str4";

To ascertain the count of commas (,') within this string, we employ the match()` function:

console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3

Alternatively, to count the number of strings created by splitting the main string along commas, we use a regular expression:

console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4

Moreover, in certain scenarios, validating the lengths of individual strings within the main string is necessary. If each string should not exceed 15 characters, this check can be implemented using a for loop:

for (let i = 0; i  15) {
        console.error(`String '${counts[i]}' exceeds the maximum length of 15 characters.`);
    }
}

By incorporating these techniques, you can effectively count character occurrences and validate string lengths in Javascript.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3