How to count the number of words in a string with JavaScript

2 Answers

0 votes
const str = "javascript php c c++";
 
const len = str.split(" ").length;
 
console.log(len); 
 
 
   
     
     
/*
run:
     
4
     
*/

 



answered Jun 4, 2021 by avibootz
edited Feb 15, 2022 by avibootz
0 votes
const str = "javascript php c c++";
 
const len = str.trim().split(/\s+/).length;
 
console.log(len); 
 
 
   
     
     
/*
run:
     
4
     
*/

 



answered Jun 4, 2021 by avibootz
edited Feb 15, 2022 by avibootz
...