Home > Web Front-end > JS Tutorial > How to Count Substring Occurrences in JavaScript Using Regular Expressions?

How to Count Substring Occurrences in JavaScript Using Regular Expressions?

Barbara Streisand
Release: 2024-12-07 09:51:17
Original
335 people have browsed it

How to Count Substring Occurrences in JavaScript Using Regular Expressions?

Counting String Occurrences in Strings

Finding the frequency of a substring within a larger string is a common task in programming. In JavaScript, you can use regular expressions to accomplish this effectively.

Consider the following example where we want to count the occurrence of the substring "is" in the string "This is a string.":

Example:

var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count); // Output: 2
Copy after login

Explanation:

  1. Regular Expression (Regex): The regular expression we use is "/is/g". The "is" part represents the substring we want to find, and the "g" flag indicates a global search.
  2. .match() Method: The .match() method is applied to the string "temp". This method returns an array of matches for the provided regular expression. However, the "g" flag ensures it finds all occurrences, not just the first one.
  3. Handling Empty Results: If the substring is not found, the .match() method returns null. To handle this case, the result is wrapped in a conditional statement that converts null to an empty array.
  4. Array Length: Then, we obtain the length of the array containing the matches. This length represents the count of occurrences for the specified substring.

As a result, the code correctly prints the count of "is" occurrences in the given string, which is 2.

The above is the detailed content of How to Count Substring Occurrences in JavaScript Using Regular Expressions?. 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