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
Release: 2024-12-02 18:35:13
Original
136 people have browsed it

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"
Copy after login

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
Copy after login

To count the occurrence of individual strings:

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

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");
  }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template