Identify line counts and hyphenated lines in a text box with the help of regular expressions

I have been struggling to find a solution to the problem of excluding lines starting with double hyphens when using regular expressions. I need to count single lines separately and double hyphenated lines separately, and display them outside the text area.

While I have managed to count each line successfully, I am unsure about how to ignore the hyphens in order to achieve an accurate count using regular expressions.

Additionally, I am facing difficulties in appending the code inside a span item as it seems to remove the text of the item element.

Below is my code snippet along with a sample image: https://i.sstatic.net/2QJQB.jpg

$(document).ready(function(){
    
    var items = $('#items');
    var groups = $('#groups');
    
    $('#ingredients_list').keydown(function(e) {
        newLines = $(this).val().split("\n").length;
        items.text(newLines);
    });
});
.ingredients__section {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.ingredients__section textarea {
  width: 100%;
}

.ingredients__section h2 {
  color:#0433a7;
  margin-bottom: 20px;
}

.ingredients__header {
  display: table;
  width: 100%;
  table-layout:fixed;
}
.ingredients__title { display: table-cell; }
.ingredients__countinfo { display: table-cell; text-align:right; }

.item-count,
.group-count { padding: 5px 15px; background-color:#e4ebef; margin-left: 5px; font-size: 14px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ingredients__section">
<div class="ingredients__header">
<div class="ingredients__title"><h2>INGREDIENTS</h2></div>
<div class="ingredients__countinfo">
  <span class="group-count" id="groups">Groups:</span>
  <span class="item-count" id="items">Items:</span>
</div>
</div>
<form>
    <textarea id="ingredients_list" rows="15"></textarea><br />
</form>

</div>

Answer №1

Start counting

let groupCounter = 0;
let itemCounter = 0;

Fetch the input text array

let arrayOfItems = $(this).val().split("\n");

Iterate through all elements in the array and check the first two symbols. If it is --, then increment groupCounter; otherwise, increment itemCounter

for (let i=0; i<arrayOfItems.length; i++) {
  if (arrayOfItems[i][0] === '-' && arrayOfItems[i][1] === '-') {
    groupCounter += 1;
    itemCounter -= 1;
    groups.text("Groups: " + groupCounter);
  } else {
    itemCounter += 1;
    items.text("Items: " + itemCounter);
  }
}

$(document).ready(function(){
    
    let items = $('#items');
    let groups = $('#groups');
    
    $('#ingredients_list').keypress(function(e) {
        let groupCounter = 0;
        let itemCounter = 0;
        let arrayOfItems = $(this).val().split("\n");
        for (let i=0; i<arrayOfItems.length; i++) {
          if (arrayOfItems[i] != '') {
            if (arrayOfItems[i][0] === '-' && arrayOfItems[i][1] === '-') {
              groupCounter += 1;
              groups.text("Groups: " + groupCounter);
            } else {
              itemCounter += 1;
              items.text("Items: " + itemCounter);
            }
          } else {
            groups.text("Groups: " + groupCounter);
            items.text("Items: " + itemCounter);
          }
        }
    });
    $(document).mousedown(function (e) {
        let groupCounter = 0;
        let itemCounter = 0;
        let arrayOfItems = $('#ingredients_list').val().split("\n");
        for (let i=0; i<arrayOfItems.length; i++) {
          if (arrayOfItems[i] != '') {
            if (arrayOfItems[i][0] === '-' && arrayOfItems[i][1] === '-') {
              groupCounter += 1;
              groups.text("Groups: " + groupCounter);
            } else {
              itemCounter += 1;
              items.text("Items: " + itemCounter);
            }
          } else {
              groups.text("Groups: " + groupCounter);
              items.text("Items: " + itemCounter);
          }
        }
    });
});
.ingredients__section {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.ingredients__section textarea {
  width: 100%;
}

.ingredients__section h2 {
  color:#0433a7;
  margin-bottom: 20px;
}

.ingredients__header {
  display: table;
  width: 100%;
  table-layout:fixed;
}
.ingredients__title { display: table-cell; }
.ingredients__countinfo { display: table-cell; text-align:right; }

.item-count,
.group-count { padding: 5px 15px; background-color:#e4ebef; margin-left: 5px; font-size: 14px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ingredients__section">
<div class="ingredients__header">
<div class="ingredients__title"><h2>INGREDIENTS</h2></div>
<div class="ingredients__countinfo">
  <span class="group-count" id="groups">Groups:</span>
  <span class="item-count" id="items">Items:</span>
</div>
</div>
<form>
    <textarea id="ingredients_list" rows="15"></textarea><br />
</form>

</div>

Answer №2

While your code works well overall, there is a small issue that I have noticed. If you input a word with double hyphens -- or without them, it increments both the groupItems and listItems by +1. This may not be the desired behavior. When starting a group name with --, the count should go up for groups instead of items.

$(document).ready(function(){

var items = $('#items');
var groups = $('#groups');

$('#ingredients_list').keypress(function(e) {
    var groupsCount = 0;
    var itemsCount = 0;
    var arrayOfItems = $(this).val().split("\n");
    console.log(arrayOfItems);
    for (var i=0; i<arrayOfItems.length; i++) {
      if (arrayOfItems[i][0] === '-' && arrayOfItems[i][1] === '-') {
        groupsCount += 1;
        groups.text("Groups: " + groupsCount);
      } if (arrayOfItems[i][0] === '.'){ // You can modify this condition to suit your needs, such as looking for numbers, letters, or expressions that start with a certain character.
        itemsCount += 1;
        items.text("Items: " + itemsCount);
      }
    }
});
});

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

Establishing a website tailored specifically to each city's needs and interests, such as city1.example.com and city2

How can I create a website with subdomains dedicated to different cities like http://philly.example.com, http://maine.example.com, and http://sandiego.example.com? The majority of the site will remain the same in terms of layout, wording, database, and int ...

The page may experience some issues in Firefox, but it functions properly in Chrome

I designed a sign-in box with email and password inputs, along with some JavaScript to change its style when filled in. The CSS I used also moves the placeholder when the input is focused. Everything was working perfectly until I tested it in Firefox. Fi ...

Display a featherlightbox popup when the page loads

Well, here's the deal. I don't have any experience with wordpress php coding at all, but I can make basic adjustments using the wordpress admin. Now I've run into an issue. I tried to use the feather lightbox js, and below is a snippet of co ...

establish connections within dynamic data table entries

As a newcomer to Javascript, I've been struggling with a particular question for some time now. The challenge at hand involves a dynamic jQuery table where I aim to hyperlink one row of the table data to a .php page in order to perform certain querie ...

Enlarging the modal overlay

My Angular/Bootstrap app features a small text area within a modal window that often contains lengthy content exceeding the size of the textarea and modal itself. I am looking to incorporate a button within the modal window that, when clicked, opens a lar ...

unable to connect a value with the radio button

I am struggling to incorporate a radio group within a list of items. I am facing difficulty in setting the radio button as checked based on the value provided. Can anyone provide me with some guidance? Here is the HTML code snippet: <div *ngFor=" ...

Passing an object in an ajax call to a function: a comprehensive guide

@model IEnumerable<HitecPoint.BlackBox.Models.SMSReportModal> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"> </script> <script type="text/javascript"> var MyAppUrlSettin ...

Implementing AngularJS to include an HTML page as a widget

I am currently in the process of learning Angular js. My goal is to incorporate another website as a part of my own webpage; within a "div" element. Here is the code I have been working on to achieve this: However, the external website may contain hyperl ...

Tips for creating a line break in extendscript for Adobe Indesign

I am currently using extendscript to generate invoices based on downloaded plain text emails (.txt). Within the text file, there are specific lines containing "Order Number: 123456" followed by a line break. I have a script that I've created using co ...

Numerous applications of a singular shop within a single webpage

I have a store that uses a fetch function to retrieve graph data from my server using the asyncAction method provided by mobx-utils. The code for the store looks like this: class GraphStore { @observable public loading: boolean; @observable ...

Could it be a problem with collision detection or an issue in my

I experimented with jQuery and HTML5 Canvas to create a prototype showcasing movement using a tile map algorithm. My challenge lies in the abnormal behavior of collision detection. To elaborate, when I move horizontally (left or right), the collision is co ...

"Why does the React useState array start off empty when the app loads, but then gets filled when I make edits to the code

I'm facing a challenging task of creating a React card grid with a filter. The data is fetched from an API I developed on MySQL AWS. Each card has a .tags property in JSON format, containing an array of tags associated with it. In App.jsx, I wrote Jav ...

Resize a div within another div using overflow scroll and centering techniques

Currently, I am working on implementing a small feature but am facing difficulties with the scroll functionality. My goal is to zoom in on a specific div by scaling it using CSS: transform: scale(X,Y) The issue I am encountering lies in determining the c ...

Encountering issues with pipes and ngModel functionality in Angular causing errors

I have a unique custom dropdown feature that binds the selected dropdown value to an input field in my reactive form using ngModel. I have also implemented a mask on the input fields using a pipe. Here is all the relevant code for this functionality: HTML ...

Place the element at the bottom of the row above

I'm utilizing Angular to retrieve a list of items from the server and exhibit them on the page using: <div class="col-sm-6 col-md-4" ng-repeat="activity in activities"> <img ng-src="[[ act.icon ]]" height="100" alt=""> <h3>[ ...

If the span id includes PHP data that contains a certain phrase

Hey there, it's my first time posting and I'm in a bit of a bind with this script... Let me give you some background information first I am trying to create a click function for a register button that will check the span id (e.g. $("#username_r ...

Unable to locate the requested document using the provided query string parameter

Searching for a specific document in my database using a query string referencing a user_id from a profile schema: ProfileSchema = Schema( user_id: type: Schema.Types.ObjectId vehicules: [VehiculeSchema] home: {type:Schema.Types.ObjectId, ref: &apos ...

The mat-table's data source is failing to refresh and display the latest

When I click on a column header to sort the table, a function should trigger and update the data. However, the data is not updating as expected. Below is the code for the function and the table: <table mat-table #table [dataSource]="dataSourceMD&qu ...

Creating an expandable search box that overflows other content: A step-by-step guide

I am facing an issue with a search box that expands when activated. However, I want the search box to break out of the Bootstrap column and overflow other content on the page. How can I achieve this? Here is the CSS code for the search box styling: .searc ...

Vuetify: the item-text attribute causing issues with v-combobox

As I embark on my journey with Vue.js and Vuetify, I've encountered a simple issue with the v-combobox component that has me stumped: Picture this scenario: I want a combobox that offers three distinct options. The code snippet below functions perfec ...