Home >Web Front-end >JS Tutorial >How Can I Count Character Occurrences and Validate Substring Lengths in JavaScript?
Find Character Occurrence Counts and String Validation in Strings
Question:
Determine the frequency of specific characters within a given string and ensure the length of individual substrings meets certain requirements.
Example:
Consider the following string:
var mainStr = "str1,str2,str3,str4"
Objective: Count the occurrences of the comma (,) character and individual strings (e.g., str1, str2, ...) in the string, with a maximum character limit of 15 for each substring.
Solution:
To count the occurrence of the comma character:
console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3
To count the occurrence of individual strings:
console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4
For string validation, ensure each substring does not exceed 15 characters:
var strs = mainStr.split(","); for (var i = 0; i < strs.length; i++) { if (strs[i].length > 15) { throw new Error("String exceeds maximum length"); } }
The above is the detailed content of How Can I Count Character Occurrences and Validate Substring Lengths in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!