DEV Community

mridul037
mridul037

Posted on

count number of word in string using javascript.

function countWords(str) {
let c=0;
for (x in str){

if(str[x]==" ")

c++;

}
return c+1;
}

Top comments (1)

Collapse
 
delixx profile image
DeLiXx

or you do

str.split(" ").length

which is not only easier to read but also faster