How to useregular expressions in Javascript
Regular expressions are powerful tools for pattern matching in strings. We can utilize regular expressions with the match() method to count occurrences of a substring within a string.
This approach involves creating a regular expression dynamically with the desired substring and the global flag ‘g’ to find all occurrences. Then, we use the match() method to find all matches of the regular expression in the string and return the count of matches.
Example: Counting occurrence of “Geeks” in “w3wiki” using regular expressions.
function countOccurrences(string, subString) {
// Escape special characters in the subString to avoid regex interpretation
const escapedSubString = subString.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Create a regular expression with the escaped subString and the global flag
const regex = new RegExp(escapedSubString, 'g');
// Use match() to find all occurrences of the subString in the string
const matches = string.match(regex);
// Return the number of matches found
return matches ? matches.length : 0;
}
// Example usage:
const string = "Geeks for Geeks";
const subString = "Geeks";
console.log(countOccurrences(string, subString)); // Output: 2
Output
2
How to count string occurrence in string using JavaScript ?
In JavaScript, we can count the string occurrence in a string by counting the number of times the string is present in the string.
This can be done in the following ways:
Table of Content
- Approach 1: Using match() function
- Approach 2: Using a loop
- Approach 3: Using split() function
- Approach 4: Using Indexof()
- Approach 5: Using regular expressions
Contact Us