How to usematch() function in Javascript
JavaScript match() function is used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array.
Example: Counting occurrence of Geeks in âw3wikiâ using the âmatch()â function.
function gfg() {
let r = "Geeks For Geeks ";
console.log(
(r.match(/Geeks/g)).length);
}
gfg()
Output
2
The âgâ in the function specifies global which is used to search for an entire string rather than stop by finding the first occurrence.
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