Organize multiline string based on regex pattern using Javascript

I need to split a multi-line string and group it by a specific regex pattern that repeats throughout the text

Some random filler
in the beginning
of the content

Checking against xyz...
Text goes here
More text
and more.

Checking against abc...
Another set of text
with more details

Based on the above example, I want to create groups based on the text following the phrase Checking against (like xyz and abc in this case), with each group containing the lines after that term up until the next occurrence.

After grouping, the output should look something like this, making it easy to access the values under each category:

{
  xyz: 'Text goes here\nMore text\nand more.'
  abc: 'Another set of text\nwith more details'
}

To achieve this, my initial plan is to divide the string into an array of elements separated by newlines, but then I'm facing difficulties in:

  • Finding occurrences of "Checking against" and assigning them as keys
  • Appending every line until the next occurrence as the value for that key

Answer №1

You might want to give this a try

const text = `Add some initial content here
to start off

Checking against apple...
Some random text goes here
More text follows
and so on.

Checking against orange...
More details provided
even more information`;

let current = null;
const data = {};
text.split("\n").forEach(line => {
    const match = line.match(/Checking against (.+?)\.\.\./);
  if (match) {
    current = match[1];
  } else if (current && line !== "") {
    if (data[current]) {
        data[current] += "\n" + line
    } else {
        data[current] = line;
    }
  }
});
console.log(data)

Answer №2

In order to achieve this task, one approach is to utilize the split method to divide the entire text based on the occurrence of "Checking against," while simultaneously extracting the word that comes after it as part of the split criteria.

After removing the introductory section using slice(1), you can convert the array of keyword-text segments into pairs, which can then be processed with Object.fromEntries to generate the desired object:

let data = `Some filler
at the beginning
of the text

Checking against foo...
Some text here
More text
etc.

Checking against bar...
More text
moremoremore`;

let result = Object.fromEntries(
    data.split(/^Checking against (\w+).*$/gm)
        .slice(1)
        .reduce((acc, s, i, arr) => i%2 ? acc.concat([[arr[i-1], s.trim()]]) : acc, [])
);
console.log(result);

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

The Mailchimp 404 JavaScript error has occurred, file missing in action

I pasted a Mailchimp embedded form directly from Mailchimp, but I encountered the following error in the console log: GET http://s3.amazonaws.com/downloads.mailchimp.com/js/jquery.min.map 404 (Not Found) Here is the HTML code for it within Rails: <li ...

Implementing automatic line breaks in Bootstrap

When setting the "overflow scroll able" option, I want it to only allow scrolling in the y direction and if x content overflows, a line break should occur. I tried applying 'white-space', but it didn't work as expected. <ul class="s ...

Assign a variable value to populate several `<input>' fields

Using a variable named multiplier, I have successfully set the value of multiple input fields. Each input now has a custom attribute called my_value that is calculated based on three drop-down menus and a target table with corresponding values. The calcula ...

Ways to minimize the occurrence of duplicate values in a table

In the application, I have a table where I add multiple values to an Array. These arrays display the values in the table columns, sometimes resulting in duplicate values. Below is a small example to illustrate the issue. What is the best way to eliminate ...

Updating the state on change for an array of objects: A step-by-step guide

In my current scenario, I have a state variable defined as: const [budget, setBudget] = React.useState<{ name: string; budget: number | null }[]>(); My goal is to update this state by using a TextField based on the name and value of each input ...

Using JQuery, ensure that the scroll function runs in advance of the ajax call finishing

I am currently working on using jQuery to scroll down to a text box when the click event occurs. However, I have noticed that the scroll event is happening after the AJAX call within the function. $("#execute_btn").click(function(){ $('html, b ...

Displaying JavaScript validation errors on a Bootstrap 4 .btn-group-toggle

I have created a star rating user interface using the Bootstrap 4 .btn-group.btn-group-toggle as shown in the code snippet below: <div class="form-group"> <div class="btn-group btn-group-toggle" data-toggle="buttons" aria-label="Rate this"> ...

What is the best way to organize objects based on their keys?

Looking to iterate through object values and append text if the key matches in JavaScript. The object is as follows: { "id": "n27", "name": "Thomas More", "className": "level-1", & ...

Dependable method for retrieving the "ancestor" of an element with a designated class name through the utilization of jQuery

I have a JavaScript function that triggers on the change event of a select form element. In this context, the "this" variable in JavaScript refers to the select element itself. The select element is nested within a td tag, which is further contained withi ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

Adjust the color of an SVG icon depending on its 'liked' status

In my React/TypeScript app, I have implemented an Upvote component that allows users to upvote a post or remove their upvote. The icon used for the upvote is sourced from the Grommet-Icons section of the react-icons package. When a user clicks on the icon ...

Guide to incorporating a component in Vue 2

I recently developed a Vue 2.5.2 application using vue-cli. While attempting to create my first component (<jsontree />), I encountered an issue as it functions independently, but I am struggling to understand how to properly register it for use in ...

What is the best way to manage optional peer dependency types while releasing a TypeScript package?

I'm trying to figure out the best way to handle optional peer dependencies when publishing a TypeScript package on npm. My package provides a function that can accept input from either one of two peer dependencies. How should I define these optional p ...

The nodejs application seems to be encountering an issue as the /public/index.html file is not displaying on the

|project-name | client | public | index.html | server.js ↑ Structure of the Project The goal is to display the index.html file (located in the public folder) in server.js. [ server.js ] const express = require('express') const app ...

Refine JSON arrays by applying combined nested array filters

Currently, I am in the process of developing a JavaScript code that aims to filter JSON data based on a specific condition. Yesterday, I had posted a question seeking guidance on this matter How to filter data from a json response. However, since I had not ...

In JavaScript, when using the fetch function with JSON, it is possible to skip the

Here's an example of fetching review data from within a 'for loop': fetch('https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline') In this case, some products may not have reviews and will return a 404 response. Th ...

Bring in NPM package that relies on another module

Recently transitioning to Meteor 1.3 with npm module support, I've encountered the following issue: TypeError: Cannot set property 'tip' of undefined Below is the relevant code snippet in myFile.js: import d3 from 'd3'; import d ...

Troubleshooting issues with Jquery, Ajax, and PHP integration

Currently, I am in the process of refreshing my knowledge on jQuery and AJAX. In jQuery in 8 hours, there is a code snippet that caught my attention: <!DOCTYPE html> <htmlxmlns="http://www.w3.org/1999/xhtml"> <head> <title>A Sample ...

Adding page numbers in a select dropdown menu without using the traditional next and previous buttons

I am attempting to implement a select tag paging feature using the code below: <select ng-change="params.page(page)" ng-model="page" ng-options="page.number as page.number for page in pages"></select> However, I noticed that when I incorporat ...

How to use Angular ngRepeat to create multiple select fields that do not show previously selected data with ng-options

Looking at the issue from a high level; I'm fetching data from an api and creating a CRUD page for it. The user can choose from a set of labels provided in the data. Here is a code snippet illustrating my dilemma. The selected labels are denoted by t ...