Splitting a string into an array based on a regular expression

I'm working with a structure that consists of either a single string array ['stufff sjktasjtjser ((matchthis))'], or the same structure in a nested array ['stufff', ['more stuff ((matchhere))'], '((andanother))']. I have the ability to loop through and match all regex patterns within the brackets, as well as replace the text:

// After flattening the array, let's focus on the first element and assume I am looping within it.
var matches = currentArrayElement.matchAll('fancyregex') // pretending to match the brackets
matches.forEach(match=>currentArrayElement=currentArrayElement.replaceAll(match[0],'whatwhat'))
console.log(currentArrayElement) //'stufff sjktasjtjser whatwhat'
// However, my desired output is actually:
// currentArrayElement = ['stufff sjktasjtjser','whatwhat'];

Can anyone provide guidance on how I can achieve this? Or suggest any template library that can handle this requirement for nested arrays? Sometimes I need to output an array of strings ['tss'], and other times an array with objects [{}].

Thank you.

Answer №1

The problem arose when I realized that only the array at a specific index needed to be modified, not the entire array.

Here is the solution I implemented:

// After flattening the array, we focus on the first element as if we are iterating through it.
var matches = currentArrayElement.matchAll('fancyregex') // Assuming brackets are being matched
matches.forEach((match) => {
      currentArrayElement[i] = c.split(match[0]).flatMap(
        (value, index, array) => (array.length - 1 !== index
          ? [value, 'whatwhat',]
          : value),
      );
    });

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

Using AngularJS to Showcase JSON Array

I am currently working with a .json file that contains information about networks, IP addresses, and zones. I am trying to figure out how to display the "ip" array in my .html file. [ { "network":"net1", "ip":[ "19 ...

Consolidate ajax calls into a single template

I am working on 2 Ajax requests to retrieve CRM details. First, I need to fetch all the order statuses in the system and create a unique container for each status ID. Then, I have another request to get all the orders and assign them to their respective st ...

Asynchronously pushing items to an array and saving with Node.js promises

I am currently attempting to populate an array (which is an attribute in a Mongo Model) with items received from a request. I iterate through these items to check if they already exist in the database, and if not, I create a new Item and attempt to save it ...

Creating three search fields in Vue.js with computed properties is a powerful and efficient way to filter

I am struggling to implement a search feature with three fields - one input and two selectors. I was able to get it to work with two fields, but adding the third is causing issues. I could really use some guidance on this. computed: { ...

Sending a global variable to another controller file in Node.js

I am facing an issue with a global variable called userEmail. The variable is supposed to hold the current user's email value, which is assigned during a post request handling authorization. However, when I try to export this global variable to anothe ...

Is the for loop programmed to stop at the first match?

I've been working on filtering a txt file using nodejs. Here's my code snippet: const fs = require('fs') let list = fs.readFileSync('./newmR.txt', 'utf-8').split('\r\n') console.log(list.length) ...

Can one retrieve a catalog of Windows Updates that have been installed by utilizing node.js?

Currently, I am working on a JavaScript/Node.js project where I am seeking to retrieve a comprehensive list of all installed windows updates, similar to how it is done using the C# WUAPI 2.0 Type Library. I have attempted utilizing WMI calls (specifically ...

WebDriverIO effortlessly converts the text extracted using the getText() command

One of my webpage elements contains the following text: <span class="mat-button-wrapper">Sicherheitsfrage ändern</span> However, when I attempt to verify this text using webdriver, it indicates that it is incorrect assert.strictEqual($(.mat ...

Assistance is required for establishing a connection between php and js. The process begins with executing a sql query to extract the necessary data, which is then encoded into JSON format

I have encountered an issue with a project I am working on solo, involving a sidecart in a PHP file with external links to SQL, CSS, and JS. The problem arose when attempting to insert necessary data into JS using JSON encoding. <?php session_start(); ...

Get the name of the form I am submitting using jQuery

Looking to create a jQuery script that can serialize the formData being submitted from any HTML page. The challenge arises when there are multiple forms on a single page - how do I distinguish which form is being submitted? My goal is to track activities o ...

When a project sets useBuiltIns to 'usage', there is an issue with importing the library generated by Webpack

I am eager to create a versatile UI component library and bundle it with Webpack. However, I encountered an issue when trying to import it into another project that has useBuiltIns: 'usage' specified in the babelrc file. The import fails with the ...

Searching and updating a value in an array using JavaScript

I need help solving a Javascript issue I'm facing. I'm working on an e-commerce project built in Vue, and I want to implement the selection of product variants on the client-side. The data format being sent to the backend looks like this: { & ...

Manipulate MySQL data in Node.js by storing it in a variable

Struggling to grasp the concepts of nodeJS/typescript and how to effectively save database query results into variables for return. Seeking assistance to solve the problem faced: Here is a method snippet that needs help: public getAllProducts(): ProductA ...

How to automatically embed a p5.js canvas into an HTML canvas with the drawImage() method

Whenever I attempt to draw the p5.js canvas into an HTML canvas using drawImage(), I always encounter this error: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type ' ...

Personalize Badge Component

I've been on the hunt for a solution to customize a badge component similar to what's seen here: https://mui.com/material-ui/react-badge/. As of now, only options for making it a dot or adding a number in a circle are available. However, I' ...

Selecting from a variety of options presented as an array of objects

I am currently working on a component that allows users to select roles: https://i.stack.imgur.com/bnb9Y.png export const MultipleSelectChip = ({ options, label, error, onRolesUpdate, }: Props) => { const theme = useTheme(); const [selected ...

"Encountering an issue where the route function in Passport and ExpressJS is not being

When using passport for admin authentication, I am facing an issue where the redirect is not calling my function. Consequently, all that gets printed on login is [object Object] Here is my code: app.get('/admin', isLoggedIn, Routes.admin); ...

Scanning through a list, searching for specific values and applying a checksum algorithm

I'm having trouble understanding this piece of code in MPLAB and where my mistake might be. Here is the starting part of the function, which I understand char validateNemaSentence(char *pSentence) { char chkSumToken[3]; unsigned char calculat ...

Challenges Encountered with AngularJS $http Service

How do I pass my data from the http request to the $scope in the MainCtrl? The code below should fetch data from a MySQL Database with an $http-service, but somehow the data provided by the service doesn't go to the controller or gets displayed incor ...

Activating Cors Support on Firefox

When working with AngularJS, I wrote the following code to make an API call: $http({ method: 'GET', url: 'https://www.example.com/api/v1/page', params: 'limit=10, sort_by=created:desc', //h ...