-1

I want to count number of sentences and Words in each sentence. This code is counting the sentences but I want to split the text by each sentence to put into an array. Kindly suggest me some better mechanism.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Count Number of Words in a String</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){
            var words = $.trim($("textarea").val()).split(".");
            alert(words.length-1);
        });
    });
</script>
</head>
<body>
    <textarea cols="50">The quick brown fox jumps. over the lazy dog.</textarea>
    <br>
    <button type="button">Count Words</button>
</body>
</html>
Sphinx
  • 10,519
  • 2
  • 27
  • 45
Basit ali
  • 1
  • 3

4 Answers4

0

If sentence is always separated with period and word always separated by space. Then you can split whole text with period as separator to get sentences and for every sentences you split it again using space as separator.

var sentences = stringFromTextArea.split('.');
var words = [];
sentences.forEach(function(sentence) {
    words.push(sentence.split(' '));
});
Zamrony P. Juhara
  • 5,222
  • 2
  • 24
  • 40
0

Here is something that would work. Although you would need to then use jQuery to write the results instead of just console logging them. This also accounts for empty sentences/words due to the splitting.

const input = 'The quick brown fox jumps. over the lazy dog.'
const result = input
  .split('.') // split the sentences
  .filter(sentence => sentence !== '') // remove empty sentences
  .map(sentence => sentence.split(' ') // split the words
  .filter(word => word !== '') // remove empty words
  .length); // get number of words in sentence

console.log(`There are ${result.length} sentences.`);
result.forEach((item, index) => {
  console.log(`Sentence ${index + 1} has ${item} words.`);
});
jens
  • 2,075
  • 10
  • 15
0

$.trim($("textarea").val()).split(".") is actually separating the text into an array of sentences already.

With this array, you can iterate through it, splitting up the words, and count each sentence that way.

var count = 0;
$.each(sentence, function(index, words){
    count += words.length();
})

Hope this helps!

Ben
  • 166
  • 1
  • 8
0

Making the assumptions you have about sentences ending in '.' and words separated by '.'

var wordsCounts = $.trim($("textarea").val()).split(".").map(getWordCount);
function getWordCount(sentence){
    return sentence.split(' ').length;
}

You now have an array of word counts. The length of the array is the number of sentences and each value stored in the array is the number of words in the sentence corresponding to the number index + 1

foxinatardis
  • 156
  • 8