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:
Approach 1: Using match() function:
match() function 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 “GeeksforGeeks” using the “match()” function.
Javascript
function gfg() {
let r = "Geeks For Geeks " ;
console.log(
(r.match(/Geeks/g)).length);
}
gfg()
|
The ‘g’ in the function specifies global which is used to search for an entire string rather than stop by finding the first occurrence.
Approach 2: Using loop
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true
Example: Counting occurrence of for in “GeeksforGeeks” using Loops.
Javascript
function gfg() {
let s = "Geeks for Geeks" ;
let f = "for" ;
let i = 0,
n = 0,
j = 0;
while ( true ) {
j = s.indexOf(f, j);
if (j >= 0) {
n++;
j++;
} else
break ;
}
console.log(n);
}
gfg()
|
Approach 3: Using split() function
split() Method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument.
Example: Counting occurrence of Geeks in “GeeksforGeeks” using split() function.
Javascript
function gfg() {
let s = "Geeks for Geeks" ;
let f = "Geeks" ;
let r = s.split(f).length - 1;
console.log(r);
}
gfg()
|
indexOf() method returns the position of the first occurrence of the specified character or string in a specified string.
Example: Counting occurrence of Geeks in “GeeksforGeeks” using indexof().
Javascript
function gfg() {
let s = "Geeks for Geeks" ;
let f = "Geeks" ;
let r = s.indexOf(f);
let c = 0;
while (r != -1) {
c++;
r = s.indexOf(f, r + 1);
}
console.log(c);
}
gfg()
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
17 Jul, 2023
Like Article
Save Article