Counting consecutive sentences starting with "The" using Javascript

As a newcomer, I am attempting to create a code that can split a copied text into sentences and then identify if three or more consecutive sentences begin with the word "The". My goal is for the program to be flexible regardless of the number of sentences in the input text, even though I currently have only five. Can anyone offer assistance?

<!DOCTYPE html>
<html>
<body>

Check for three or more sentences in a row starting with "The".



<form id = "quiz" name = "quiz">

<input id = "text1" type = "text" name = "question1"> <!here you are supposed to paste the text you want to check>
<input id = "button" type = "button" value = "Split into sentences" onclick = "Split();">




<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>





<script>
function Split() {
 question1 = document.quiz.question1.value; 
let text = question1;
const myArray = text.split(/[\\.!?]/); //this splits the text into sentences
var x=0
var y=x

document.getElementById("demo1").innerHTML = myArray; //here I write the sentences

let result1 = myArray [0].startsWith("The"); //here I don't have a space before the word "The" as a text normally don't start with a space.
let result2 = myArray [1].startsWith(" The");
let result3 = myArray [2].startsWith(" The");
let result4 = myArray [3].startsWith(" The");
let result5 = myArray [4].startsWith(" The"); //now I only have five sentences but I would like the program to check the text regardless of how many sentences the pasted text includes. How do I achieve that?




{document.getElementById("demo3").innerHTML = 'You have '+(result1 + result2 + result3 + result4 + result5) + ' sentences that starts with "The".';} // Here I count the sentences that starts with "The". But I would like to only count if three (or more) sentences next to each other starts with "The" and to let the program write something like "You have three sentences (or more) next to each other that starts with 'The'" and to inform the user of the program which the first sentence of these three (or more) consecutive sentences that starts with "The" is.





}
</script>

</body>
</html>

Answer №1

If you want to find sentences starting with "the" or " The", try adding this code snippet to the end of your Split function:

let matches = [];
for (var j = 0; j < myArray.length; j++) {
   if (myArray[j].toLowerCase().startsWith("the") || myArray[j].toLowerCase().startsWith(" the")) {
       matches.push(myArray[j]);
   }
}
document.getElementById("results").innerHTML = 'There are ' + matches.length + ' sentences that start with "The".';

This code snippet iterates through the input array and adds matching sentences to a new array. The length of the new array indicates how many matches were found. You can modify the startsWith(" the") condition by adjusting your regular expression to also handle leading spaces.

Answer №2

If you find yourself repeatedly typing out the same code lines, it's a good indicator that you may need to implement a loop. This is especially helpful for beginners in coding. If you constantly see yourself repeating tasks or copying and pasting, it's time to consider using loops!

One strategy to determine the number of sentences in a block of text is by counting the periods. Regular expressions (regex) can be quite handy for this task, despite their complexity. They provide a powerful toolset for such operations.

let sentenceCount = text.match(/[.]/g).length; // Using regex

For those interested in learning more about regular expressions, resources like Regexr offer comprehensive explanations. Once we know the sentence count, we can proceed by looping through the text lines.

let totalMatches = 0;
for(let j=0; j < sentenceCount; j++){
   if(myArray[j].startsWith("The")){
      totalMatches++;
}

This code snippet ensures flexibility in handling any number of text lines efficiently. Remember, mastering loops is crucial in programming as it can significantly reduce redundant efforts and save time. For further insights on looping, check out this article: looping article. Embrace problem-solving skills, analyze your code, and keep advancing! Stay curious and dedicated. Research is key in the developer's world, where understanding precedes implementation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble copying an iframe from one div to another div?

I'm having trouble transferring an iframe to another div. Here is the code I am using: <script type="text/javascript"> $(document).ready(function () { setInterval(function () { if ($('#d1').html() != $('#d ...

What are some superior methods for determining the validity of a control in JavaScript?

Is there a way to determine the validity of a control in JavaScript within Asp.Net using a client-side API? Specifically, I am looking for a function that can check if a control is valid based on attached validators. For example, if a textbox has 2 validat ...

Prevent mouse over scrolling for every <select> element on a webpage using JQuery

My code seems to be having some issues. Can you help me figure out what's wrong? <script type="text/javascript" language="javascript"> //trying to disable scrolling on mouse over of <select> elements $(document).ready(function() { ...

Error: Visual Studio Code is unable to locate the module 'typegram/callback'

Currently, I am developing a telegram bot utilizing the telegraf package (version 4.1.1). Everything was functioning perfectly until I incorporated additional modules from the telegraf package such as Extra and mark-up. Unfortunately, I encountered the f ...

Challenge in Decision Making

I am curious why this type of selection is not functioning properly for html select options, while it works seamlessly for other input types like Radios or checkboxes. Any thoughts? $('#resetlist').click(function() { $('input:select[nam ...

What is the best way to target a specific item in a list using JavaScript in order to modify its appearance?

How can I modify the appearance of a specific li element when it is clicked? ...

Exploring ways to utilize fetch results within a return statement in React

I have fetched data that is displayed as shown below. Now, I am trying to figure out how to render this fetch in the return statement within the results div. Does anyone have any ideas on how to achieve this? I attempted using a map function because I assu ...

Extracting information from a Weather API and sharing it on Twitter

Can anyone help me troubleshoot my Twitter bot setup for tweeting out city temperatures? I attempted switching to a different API, but nothing seems to be resolving the issue. console.log('initiating twitter bot...') var Twit = require('t ...

A step-by-step guide on simulating a click event on an element in React with the help of jest and react-testing

My component displays the following {list.options && list.options.length > 0 ? ( <div data-testId="MyAlertText" onClick={onAddText}> Add Text </div> ) : null} When testing, I am executing the following it('Ensure Add Text lin ...

Obtain the name of the checkbox that has been selected

I'm new to JavaScript and HTML, so my question might seem silly to you, but I'm stuck on it. I'm trying to get the name of the selected checkbox. Here's the code I've been working with: <br> <% for(var i = 0; i < ...

Constructing an Http Post URL with form parameters using the Axios HTTP client

I need assistance in creating a postHTTP request with form parameters using axios on my node server. I have successfully implemented the Java code for constructing a URL, as shown below: JAVA CODE: HttpPost post = new HttpPost(UriBuilder.fromUri (getPro ...

I constantly encounter the error message "Unable to access properties of undefined (reading 'map')"

I am in the process of using Nextjs 13 for developing my front end and I have a requirement to fetch a .json file from a URL and utilize it to populate my website through server side rendering. However, I keep encountering an error saying "Cannot read prop ...

Retrieve an array from the success function of a jQuery AJAX call

After successfully reading an rss file using the jQuery ajax function, I created the array function mycarousel_itemList in which I stored items by pushing them. However, when I tried to use this array in another function that I had created, I encountered t ...

What is the best way to determine the number of non-empty entries within a PHP array?

Consider: [uniqueName] => Array ( [1] => uniqueName#1 [2] => uniqueName#2 [3] => uniqueName#3 [4] => uniqueName#4 [5] => [6] => ...

Can the pointer to a dynamically allocated array be duplicated before memory is allocated for it?

Apologies if this question has been raised previously, as I have not found the answer yet. I was surprised that the code below does not output "300" as expected: #include <iostream> int main() { int *array; int *arrayCopy = array; array = n ...

Integrating a Google map into an Ionic Side-Menu application

I am trying to incorporate a Google map into my Ionic app. I followed the code provided in this https://developers.google.com/maps/documentation/javascript/adding-a-google-map and it worked fine in Angular, but not in my side-menu Ionic project. The specif ...

call a custom form submission using jquery first, followed by a regular form submission

Is it possible to attach a submit() handler to a form in order to execute an ajax request, and then have the form submit itself normally once the request is complete? Using $('#myForm').submit() seems to just result in the same function being cal ...

Remove a div element with Javascript when a button is clicked

I am working on a project where I need to dynamically add and remove divs from a webpage. These divs contain inner divs, and while the functionality to add new divs is working fine for me, I'm facing some issues with removing them. The code snippet b ...

React-select allows for multiple selections within a component when the onChange function

I am currently utilizing react-select. Per the official documentation, it recommends using 'isMulti' to select more than one option. Below is the custom component that I have created. import React from 'react'; import { Form } from &ap ...

Creating interactive button groups with responsive design in a Material UI and ReactJS web application

Is it possible to make ButtonGroup Buttons responsive? I heard about an attribute called "Orientation" in material-ui's ButtonGroup, but I'm not sure how to use it with media queries for changing orientation based on the device width. I'm st ...