Challenges with extracting and organizing dates using JavaScript regular expressions

My task involves organizing these text rows into specific groups based on certain criteria and names.

Il Messaggero Roma 22 settembre 2023
Il Messaggero Roma 21 settembre 2023
Il Messaggero 22 settembre 2023
Il Messaggero 21 settembre 2023
Il Messaggero Roma 21 agosto 2023
Il Messaggero Roma 20 agosto 2023
Le Grandi Glorie del Rock – 15 febbraio 2023
Corriere della Sera Sette 26 agosto 2023

The goal is to group them like this:

Il Messaggero Roma [settembre 2023]
Il Messaggero Roma [agosto 2023]
Il Messaggero [settembre 2023]
Le Grandi Glorie del Rock - [febbraio 2023]
Corriere della Sera Sette [agosto 2023]

Unfortunately, the current grouping is incorrect, with some items included erroneously under wrong names:

settembre [settembre]
agosto [agosto]
febbraio [febbraio]

For example, "

Corriere della Sera Sette 25 Agosto 2023
" and "Il Messaggero" are incorrectly grouped under:

settembre [settembre]
agosto [agosto]

I have attempted to resolve this issue using the following code:

Function for grouping texts such as Il messaggero 21 settembre 2023 or

Le Grandi Glorie del Rock – 15 febbraio 2023

function groupByDate(data) {
    // Code implementation goes here
}

Regex pattern used for matching

function extractGroup(text) {
    // Regex function details here
}

Initialization of table data

function initializeDataTable(data) {
    // Table initialization logic
}

You can find the complete code for table initialization HERE. However, I believe it may not be relevant for solving the current issue.

Answer №1

To create a grouping key, you must extract the part of the text before the date while excluding the day number. You can achieve this using a regular expression replacement.

function groupByDate(data) {
  var groupedData = {};
  data.forEach(function(item) {
    var date = item.id.replace(/^(.*?)\d{1,2}\s((?:january|february|march|april|may|june|july|august|september|october|november|december)\s\d{4})/i, '$1[$2]');
    if (date != item.id) {
      key = date[0].toLowerCase();
    } else {
      key = 'other';
    }
    if (!groupedData[key]) {
      groupedData[key] = [];
    }
    groupedData[key].push(item);
  });
  return groupedData;
}

Answer №2

My approach involves creating 2 functions for each radio button or badge option.

function extractGroup(text) {
    var containsNxM = /\d+x\d+/.test(text);
    if (containsNxM) {
        var match = text.match(/^([a-zA-Z\s]+\s\d+x)/);
        return match ? match[0] : '';
    } else {
        return text;
    }
}

Additionally, I have another function:

function groupNewspapers(text) {
  var containsHash = /#\s\d+\s\w+\s\d+/g.test(text);
  if (containsHash) {
    var match = text.match(/^([a-zA-Z\s]+)\s#\s\d+\s(\w+\s\d+)/gm);
    return match.map(function(line) {
      return line.replace(/^([a-zA-Z\s]+)\s#\s\d+\s(\w+\s\d+)/, '$1 # $2').replace(/^\d+\s\w+\s/, '');
    }).join('\n');
  } else {
    return text;
  }
}

When it comes to table initialization, I have updated the code as follows:

function initializeDataTable(data) {
    if (dataTable) {
        dataTable.destroy();
    }
    var tableData = [];
    if (grouped) {
        groupedData = {};
        data.forEach(function(item) {
            var groupName;
            if (item.badge === 'serietv') {
                groupName = extractGroup(item.id);
            } else if (item.badge === 'quotidiani') {
                groupName = groupNewspapers(item.id);
            }

            if (!groupedData[groupName]) {
                groupedData[groupName] = [];
            }
            groupedData[groupName].push(item);
        });

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

What is the process for inserting or removing a row with Javascript?

Currently, I am in the process of working on some HTML/PHP code which is displayed below. <h3 style="text-align:center;margin-top:45px;">Sitting Days</h3> <div class="sitting-days" style="display:flex; justify-content:center; margin-bottom ...

When using the parseFloat function with a regular expression input, it results

My goal is to adjust float values within a string by a specific amount. Here is my current approach: var string = '<path d="M219.6,-71.4C249,19.1,212.7,130.9,135.7,186.8C58.8,242.7,-58.8,242.7,-135.7,186.8C-212.7,130.9,-249,19.1,-219.6,-71.4C-19 ...

Vue enables components to be used in any part of the application, not limiting them to

Currently, I am initializing my Vue instance in the following manner: import ListClubsComponent from "./components/clubs/list-clubs.vue"; new Vue({ el: "#app", components: { "list-clubs": ListClubsComponent } }); It seems to be functi ...

What is the best way to initiate an onload event from a script embedded within a jquery plugin?

Currently, I am in the process of developing a jQuery plugin. One issue that I have encountered involves a script tag being dynamically added for LivePerson.com. The script is supposed to trigger an onLoad function specified in the configuration. However, ...

Discovering the Voice Channel of a User using Discord.js v13

I'm currently working on a 'wake up' command for my bot that should move the mentioned member between 2 specific voice chats and then return them to their original VC. I've successfully got the bot to move me between those 2 VCs, but no ...

Merging Two Angular Pages within a Jhipster Application

My jhipster application is simple, generating 2 entities: Product and Category. The generated pages to list the data for these entities can be found here. Specifically, there are pages for Product and Category. If I want to create a new page that combines ...

Creating a dynamic input box that appears when another input box is being filled

I have a form set up like this: <FORM method="post"> <TABLE> <TR> <TD>Username</TD> <TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD> </TR> <TR> <TD>A ...

What is the most efficient way to apply a single click handler instead of using multiple click handlers for the same

Check out the project I'm currently working on by following this link: The link provided above contains a list of clickable colors available on the right side. When a user clicks on a color, the images on the left side change accordingly. Below is t ...

Managing asynchronous data using rxjs

I created a loginComponent that is responsible for receiving an email and password from the user, then making an HTTP request to retrieve the user data. My goal is to utilize this user data in other components through a service. Here is the login componen ...

Populate a div using an HTML file with the help of AJAX

In my main HTML file, there is a div element: <div id="content"></div> Additionally, I have two other HTML files: login.html and signup.html. Furthermore, there is a navigation bar located at the top of the page. I am curious to know if it i ...

Submitting a form using jQuery and processing the response

Can a form be submitted using jQuery without utilizing json, ajax, or other methods for handling the result? For example: <form id="loginform"> //some input fields and a submit button. </form> And then with jQuery: $("#loginform").sub ...

Please provide either a render prop, a render function as children, or a component prop to the Field(auto) component

While working on my project and implementing an Auto complete feature using final-form, I encountered the following error: Must specify either a render prop, a render function as children, or a component prop to Field(auto) In order to resolve this issue ...

"JavaScript function to add objects to an array when button is clicked

var householdData = []; function createMember(age, relationship, smoker) { this.age = age; this.relationship = relationship; this.smoker = smoker; } addBtn.addEventListener("click", addHouseholdMember); function addHouseholdMember() { var ...

Utilizing SlickGrid and DataView for calculating totals efficiently without the need for grouping

I am attempting to utilize Slick Grid and DataView to calculate column totals similar to the example shown here: . However, I do not want to group my rows. Therefore, I attempted not passing a getter and formatter into the dataView.setGrouping(..) method. ...

How to use the v-model to round up a number in Vue.js

I need to round up a number in my input field: <b-form-input id="amount_input" type="number" v-model="Math.ceil(form.contract.reward_cents / 100)" :state="validate(form.contract.reward_cents)"/> ...

Using Jquery to make an Ajax request to an Asp.net Web Method

My current approach involves using a jquery method to transmit only the member identification # from the client side to the server side. On the server side, I have a traditional Web Method in place to receive the data and execute SQL queries accordingly. ...

Improving the method of accomplishing a task using AngularJS

Clicking on an item in the tobeclicked list will transfer the data to the find empty list. The goal is to locate an empty list and update it by cloning the image there. The actual values and lists will include images. When an image is clicked, the system s ...

Can you provide a database of words for different cities, towns, and countries in MongoDB (or in JSON

Currently, I am in the process of developing an application that utilizes MongoDB. One specific feature I am working on implementing is an 'auto-suggest' functionality on the front-end. For example, as a user begins to type the first few letters ...

Trouble with parsing dates in JavaScript using Moment.js

I'm retrieving dates from SQL Server that are passing through ASP.NET, and then iterating through a list of objects in jQuery to display the dates along with other data. However, regardless of the various date/time values coming from the database, the ...

Troubleshooting issue with node.js 13 import functionality

$ node --version v13.8.0 We will now proceed to create three files: // package.json { "type": "module" } // foobar.js function foo() { console.log('foo') } export default {foo} // index.js import Foo from './foobar ...