DEV Community

loading...

count number of word in string using javascript.

mridul037 profile image mridul037 ・1 min read

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

if(str[x]==" ")

c++;

}
return c+1;
}

Discussion (1)

pic
Editor guide
Collapse
delixx profile image
DeLiXx

or you do

str.split(" ").length

which is not only easier to read but also faster