How to count the occurrences of a word in a string using JavaScript

5 Answers

0 votes
function countOccurences(s, word) { 
    const arr = s.split(" ");

    let count = 0; 
    for (let i = 0; i < arr.length; i++) { 
        if (word == arr[i]) 
            count++; 
    } 
   
    return count; 
} 
   
const s = "javascript c python php c++ javascript php php c# javascript"; 
const word = "javascript"; 
 
console.log(countOccurences(s, word)); 
 
 
 
 
/*
run:
 
3
 
*/

 



answered Jan 24, 2021 by avibootz
0 votes
const s = "javascript c python php c++ javascript php php c# javascript"; 

let count = (s.match(/javascript/g) || []).length; 
 
console.log(count); 
 
 
 
 
/*
run:
 
3
 
*/

 



answered Jan 24, 2021 by avibootz
edited Jan 24, 2021 by avibootz
0 votes
const s = "javascript c python php c++ javascript php php c# javascript"; 
const word = "javascript"; 
 
const re = new RegExp(word, 'g');
 
let count = s.match(re).length; 
  
console.log(count); 
  
  
  
  
/*
run:
  
3
  
*/

 



answered Jan 24, 2021 by avibootz
edited Jan 24, 2021 by avibootz
0 votes
const s = "javascript c python php c++ javascript php php c# javascript"; 
const word = "javascript"; 
 
console.log(s.split(word).length - 1); 
 
 
 
 
/*
run:
 
3
 
*/

 



answered Jan 24, 2021 by avibootz
0 votes
function countOccurrences(str, word) {
    return str.split(' ').reduce((count, currentWord) => {
        return currentWord === word ? count + 1 : count;
    }, 0);
}

const s = "javascript c python php c++ javascript php php c# javascript"; 
const word = "javascript"; 

console.log(countOccurrences(s, word)); 

 
    
/*
run:
    
3
   
*/
 
 

 



answered Feb 28 by avibootz
...