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

utilizing jQuery to create dynamic data changes based on JSON file

<div id="rightside"> <h1>John Doe</h1> <p>1980 - 2020 <p><a href="johnswebsite.com">Visit Website</a> <p>Lorem ipsum dolor sit amet, consectetur adi ...

Jest - Silence greets the test results

Struggling with Jest has been a common theme for me ever since I first attempted to use it. Regardless of the tests I run or the options I try to pass to Jest, I never seem to get the expected 'Pass' or 'Fail' results in the console. In ...

Navigate through each element with a specific class name in a block of HTML code using

Currently, I am dealing with an HTML string that is being retrieved through AJAX. Let's assume it looks like this: var htmlString = '<div class="post"></div><div class="post"></div>'; I want to find a way to iterat ...

Using Typescript with Material UI Select

I have implemented a dropdown menu using Material UI select labeled "Search By." When the menu is clicked, it displays a list of options. I aim to store the selected option and update the label "Search By" with the chosen option. export default function U ...

Requesting data from a server using jQuery's AJAX functionality

Currently, I am utilizing the following piece of code for an ajax call: $('#filter').submit(function(){ var filter = $('#filter'); $.ajax({ url:filter.attr('action'), data:filter.serialize(), // form ...

Utilizing JavaScript in AJAX Responses

Can I include JavaScript in an AJAX response and run it, or should I only use JSON or plain HTML for a more elegant solution? I'm trying to figure out the best way to handle AJAX requests that involve inserting HTML or running JavaScript based on user ...

Error in Next.js: The function (0 , firebase_auth__WEBPACK_IMPORTED_MODULE_1__.onAuthStateChanged) is not defined as a function

Just starting out with Next.js development and currently following a Youtube tutorial on creating a Whatsapp clone using firebase8.9 as the database. I am looking to implement a feature where the app checks if the user is logged in, if so redirect them to ...

Puppeteer: Eliminate hyperlinks on webpage

I am currently using Node.js and Puppeteer to convert a webpage into a .pdf-file. Everything functions as expected, however, I need assistance in removing all the links on the page before converting it to a .pdf. This is necessary because the resulting .p ...

Storing an Excel file with JavaScript: A comprehensive guide

I've been struggling to save an Excel file using Javascript, but I'm facing compatibility issues with different browsers. I initially tried using BASE64 along with data URL, which worked well in Chrome and Firefox but failed in IE and Safari. ne ...

When invoking a function within another function, it is essential to ensure that both values are returned within the function

When calling a function within another function function1(){ return this.a } function2(){ return this.b } To output in string format, you can call function1 inside function2 function2(){ var resultOfFunction1 = this.function1(); return resultOfFunction1 ...

What is the best way to steer a vehicle in the desired direction by utilizing the arrow keys on the keyboard?

Image1 Image2 While using visual studio code, I noticed that I can move a car forwards and backwards with the arrow keys on the keyboard. However, it doesn't seem to turn when I try to move in opposite directions. Is there a way to achieve this thro ...

Creating a Map Using HTML and JavaScript

My current project involves creating a simple map that can be moved with mouse drag functionality, featuring images such as islands. I have successfully retrieved the mouse position by declaring variables posX and e.clientX, as well as for e.clientY. Howe ...

Is it feasible to utilize math.max with an array of objects?

When it comes to finding the largest number in an array, solutions like this are commonly used: var arr = [1, 2, 3]; var max = Math.max(...arr); But how can we achieve a similar result for an array of objects, each containing a 'number' field? ...

Whenever I adjust the layout of the navigation bar, the edges end up getting clipped

I'm having trouble with the border shape of my navbar. When I try to make it a rounded pill shape, the edges get cut off instead of being properly displayed. https://i.stack.imgur.com/sUN2Y.png Below is the HTML template: <template> <div cl ...

Differences between throwing errors, returning error objects, and using callbacks in Javascript

Currently, I am developing an assembler and simulator for a simplistic assembly language that my computer science students use during their classes. The project is being written in JavaScript with the intention of creating a user-friendly interface in the ...

The body parser is designed to efficiently parse and handle both gzip and json formatted HTTP POST request bodies

I've set up an API endpoint to manage http POST requests from a client. At the moment, I'm using Express framework and bodyParser to handle request bodies. What I need help with is configuring body-parser to effectively handle cases where request ...

Ways to activate an event based on the dimensions (width/height) of

Exploring ways to implement an if statement based on specific width/height values using this code example. Check out the code snippet here My approach: <p id="confirmation">Try again!</p> <script> if (new dynamicSize.width() < ...

Issue with jQuery click event not firing on multiple buttons with identical names

These are the two buttons that appear multiple times but do not function: <button name='btnEditar' class='btn btn-outline-success me-4' data-bs-toggle='modal' data-bs-target='#staticBackdrop'><i class=&a ...

REACT performance impacted by slow array filtering

I have a custom listbox feature, where a div holds a vertical list of other div elements. There is also an input field for searching within the list. While it works fine with small data sets, it becomes extremely slow with large amounts of data. In additi ...

Executing the onSuccess callback in Ajax without any ability to manipulate the ajax requests

My dilemma lies in needing to execute a JavaScript function upon the successful completion of an AJAX call. Unfortunately, I am unable to directly manage the AJAX calls as they are handled by the DNN5 framework. Is there a way for me to trigger my functio ...