Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu October 03, 2022 › #HowTo #Javascript

Count sentences in string with Javascript

In this article, you will learn how to count how many sentences are present in a string using Javascript.

Suppose, you want to create a online sentences or words counter using Javascript, then you should use the below method.

Demo - sentences counter using Javascript.
<script>
 const myText = "This is a paragraph. Is it?";
 const stop = /[.!?]/;
 const sentence = myText.split(stop);
 console.log(sentence.length - 1);
</script>
Try it Yourself »
  1. First, we will create a variable with two sentences (according to your choice).
    const myText = "This is a paragraph. Is it?";
  2. We have to create one more variable for the stop keywords (question mark, full stop, exclamation mark).
    const stop = /[.!?]/;
  3. Now, we will split the sentences using the Javascript split() method and store in a variable.
    const sentence = myText.split(stop);

    The sentence variable will return the following array.

    🔽Array
     0:"This is a paragraph"
     1:"Is it"
     2:" "
     length:3
      
  4. Now, we can use the length property of the array to get the number of how many sentences are in the string.
    console.log(sentence.length - 1);
save
listen
AI Answer
Write Your Answer
loading
back
View All