Build a Sentence Analyzer - Step 7

Tell us what’s happening:

The getWordCount function gives me the correct answers, I think.
Even with an empty string or only spaces.
Can’t figure out why I do not pass the test.

Your code so far

function getVowelCount(sentence) {
  const vowels = "aeiou";
  let count = 0;

  for (const char of sentence.toLowerCase()) {
    if (vowels.includes(char)) {
      count++;
    }
  }
  return count;
}

const vowelCount = getVowelCount("Apples are tasty fruits");
console.log(`Vowel Count: ${vowelCount}`);

function getConsonantCount(sentence) {
  const consonants = "bcdfghjklmnpqrstvwxyz";
  let count = 0;

  for (const char of sentence.toLowerCase()) {
    if (consonants.includes(char)) {
      count++;
    }
  }
  return count;
}

const consonantCount = getConsonantCount("Coding is fun");
console.log(`Consonant Count: ${consonantCount}`);

function getPunctuationCount(sentence) {
  const punctuations = ".,!?;:-()[]{}\"'–";
  let count = 0;

  for (const char of sentence) {
    if (punctuations.includes(char)) {
      count++;
    }
  }
  return count;
}

const punctuationCount = getPunctuationCount("WHAT?!?!?!?!?");
console.log(`Punctuation Count: ${punctuationCount}`);


// User Editable Region

function getWordCount(sentence){
  if (sentence === ("") || sentence === (" ") || sentence === undefined){
    return 0;
  } else {return sentence.trim().split(/\s+/).length};
}

let wordCount = getWordCount()
console.log(`Word Count: ${wordCount}`);

// User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36

Challenge Information:

Build a Sentence Analyzer - Step 7

https://www.freecodecamp.org/learn/full-stack-developer/workshop-sentence-analyzer/step-7

Ok, now I see that there is a problem when there are just 2 spaces in the string.

Why does the 2nd space turn into a word?

what does this do when there are multiple spaces?

1 Like

I suggest this site for testing and analyzing regex

https://regex101.com/

1 Like

Oops, so a space after a space turns into a word.

Thanks to both of you!

1 Like