JavaScript: how to count the number of sentences in a text

JavaScript: how to count the number of sentences in a text

In JavaScript we can count the number of sentences in a text.

In JavaScript we can count the number of sentences in a text.

The solution is as follows:


'use strict';

const countSentences = text => {
     return text.split(/[.?!]/g).filter(Boolean).length;
};

The function takes as input a parameter called text, which represents the text on which we want to count the sentences.

Within the function, the split() method on text is used. This method splits a string into an array of substrings, using a specified separator. In the case of the countSentences function, the separator used is the regular expression /[.?!]/g.

The regular expression [.?!] indicates that we want to split the text whenever we encounter a period, question mark, or exclamation mark. The g flag indicates to perform the global search, i.e. to find all occurrences of the separator in the text.

Then, the split(/[.?!]/g) method splits the text into an array of substrings, using periods, question marks, and exclamation marks as separators.

Next, the filter() method is used on the array obtained from the previous step. The filter() method creates a new array containing only the elements that satisfy a given condition. In this case, the Boolean function is used as a condition, which filters out the elements that evaluate to "true".

This step is necessary to eliminate any empty elements that may be present in the substring array. For example, if there are two consecutive periods in the text, the array will contain an empty substring between them. Using filter(Boolean), this empty substring is removed from the array.

Finally, the length of the array obtained after applying the filter() method is returned. The length of the array corresponds to the number of sentences in the text.