0

New to javascript here. I'm trying to create a javascript function that takes a text argument and counts the number of words, characters, and spaces in the text.

I'm having trouble adding the "number of words" to my function:

function superCounter (string) {
  var x = string.length,
      numSpaces = 0;
  for (var i = 0; i < x; i++) {
    if (string.charAt(i) == " ") {
      numSpaces++;
    }
  var y = 0 {
  for (var i = 0; i < string.length,
    if (string.charAt(i) === " ") {
       y = +1;
   }
   y += 1;
  }
  return {
    "characters" : x - numSpaces,
    "spaces": numSpaces
  };
}
superCounter("Work hard in silence, let success make the noise");
brianchangdev
  • 27
  • 1
  • 7

1 Answers1

0

Your function has some errors in it, so I rewrote it. How about this approach?

function superCounter (string) {
  var spaceCount = 0;
  var charCount = string.length
  for(var i = 0; i < charCount; i++){
    if(string[i] === ' '){
      spaceCount++;
    }
  }
  return {
    "characters" : charCount,
    "spaces": spaceCount,
    "words": string.split(' ').length
  };
}
superCounter("Work hard in silence, let success make the noise");
Tyler McGinnis
  • 34,836
  • 16
  • 72
  • 77
  • thanks i appreciate the help. Your code looks a lot simpler than what mine looked like before. Can you explain your code to me in a way a beginner can understand? – brianchangdev Oct 18 '15 at 07:40
  • Yup. You want to find three things. 1) How many characters the string has. 2) How many spaces it has. 3) How many words is has. So lets worry about each of these individually. 1) characters - We know we already have a way to do this in JavaScript with the .length property on strings. So by doing string.length we get the amount of characters. 2) spaces - There's no built in way to do this so we need to loop over the string and count how many times we see a space. 3) We can use .split to split your string into an array at every space ' ' then get how many items are in the array with .length. – Tyler McGinnis Oct 18 '15 at 17:57