0

I am trying to count the number of sentences in an array using the .forEach iterator on an array. Each time there is a full stop ('.') or an exclamation mark ('!'), it should increment a counter by 1. I was wondering if it was possible to do this using a Javascript iterator.

The array I am filtering through is called betterWords.

The code below returns 0 for some reason and I'm not sure why.

let sentences = 0;
betterWords.forEach(word => {
  if (word === '.' || word === '!') {
     return sentences+=1
  }
});
console.log(sentences)
6
  • 1
    What exactly is in the betterWords? Commented Dec 9, 2021 at 23:31
  • It was a string which has had a .split(' '); method applied on it. Commented Dec 9, 2021 at 23:33
  • 1
    @stormshadow854 None of the words in a sentence consist of only . or ! Commented Dec 9, 2021 at 23:34
  • @Bergi yeah there's a word paired with a '.' or '!'. How would I isolate just the '.' or '!' Commented Dec 9, 2021 at 23:37
  • 1
    if (word[word.length -1] === '.' || word[word.length -1] === '!') { Commented Dec 9, 2021 at 23:43

2 Answers 2

3

I gather that the OP aims to count sentences in a string by counting sentence-terminating punctuation marks like . ! ? (did I miss any?) A regex match will do it. Just count the matches.

const countPunctuation = string => {
  return (string.match(/[.!?]/g) || []).length
}

console.log(countPunctuation("This is a sentence. This is definitely a sentence! Is this a sentence?"))

Sign up to request clarification or add additional context in comments.

Comments

0

Your solution was almost correct:

const betterWords = "Hello World! This is a nice text. Awesome!"
let sentences = 0;
betterWords.split('').forEach(word => {
  if (word === '.' || word === '!') {
    return sentences += 1
  }
});
console.log(sentences)

You can not run .forEach on strings. You can only do this on Arrays. With split('') you can transform your string to an array. "ABC" => ["A", "B", "C"]

Using Regex like @danh did is a faster way to solve this problem.

1 Comment

You can run a for-of iterator, which in effect is the same as forEach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.