Home >Web Front-end >JS Tutorial >How Can I Count Character Occurrences and Validate Substring Lengths in JavaScript?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 18:35:13130browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn