Splitting a JavaScript string into a two-dimensional array

Can someone assist me with splitting a string into a two-dimensional array?

This is an example of my input array:

var str = 'a) first sentence without fixed length b) second phrase c) bla bla bla'

The desired output array should look like this:

var arr =[
          [ 'a', 'first sentence without fixed length' ],
          [ 'b', 'second phrase' ],
          [ 'c', 'bla bla bla' ]
         ];

I've attempted to use regular expressions to find the index of each list item, with no success. Any suggestions on how to achieve this?

Answer №1

In this solution, the goal is to extract specific patterns from a given string using a combination of split and match functions. The approach taken here focuses on identifying whitespace, followed by a letter enclosed in parentheses, and another whitespace. This method ensures accuracy even when dealing with complex parenthesis usage.

var str = 'a) first sentence without fixed length b) second phrase c) bla bla bla';
var re = /(?=\s\w\)\s)/g;
var myArray = str.split(re);
var text;
var parenIndex;

for (var i = 0, il = myArray.length; i < il; i++) {
    text = myArray[i];
    parenIndex = text.indexOf(')');
    myArray[i] = [text.substring(0, parenIndex - 1), text.substring(parenIndex + 1)];
}

Another alternative, though less reliable, assumes that every ')' acts as a delimiter for splitting the string.

var str = 'a) first sentence without fixed length b) second phrase c) bla bla bla';
var re = /(?=\w\))|\)/g;
var myArray = str.split(re);
var newArray = new Array(myArray.length / 2);

for (var i = 0, il = myArray.length; i < il; i += 2) {
    newArray[i / 2] = [myArray[i], myArray[i + 1]];
}

Answer №2

Here's an efficient method to achieve this:

let text= 'a) first approach without specific length b) another example c) more text here'
.split(/(\w)\) /)
.slice(1)
.map(function(item, index, array){if(index % 2){ return [array[index-1], item] }})
.filter(Boolean);

alert(JSON.stringify(text, null, "\t"));

   /* Output: 
 [
    [
        "a",
        "first approach without specific length "
    ],
    [
        "b",
        "another example "
    ],
    [
        "c",
        "more text here"
    ]
]
*/

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 issue at hand is that even though the network request is successfully being sent, the expected data is not being returned

Below is a javascript function that I am working with: function test() { jQuery.post("http://www.example.com/test.php", {}) .done(function(data) { alert(data); }) .fail( function(xhr, textStatus, errorThrown) { console.log(xh ...

Creating a clickable image link on a website using JavaScript: Tips and tricks

I'm looking to implement a specific feature on a website using JavaScript: <a href="URL"><img src="IMG_URL"></a>. I believe there are three key steps involved: When the site loads, JavaScript will send a request (possibly through a ...

Getting URL parameters in VueJS after a page redirect has occurred

Currently, I am implementing a Login with Facebook feature in my VueJS application using a Third Party Service (AWS Cognito). The process involves clicking on a "Login with Facebook" button which triggers a redirect to the third party URL where a Sign Up ...

Remove a specific div element using the keyword "this" in Javascript

Is there a way to generate a new div by pressing a button, with an option to delete that specific div by clicking on another button within it? I want each new div created by the first button to have its own unique delete button that will only remove its ...

Error: Module not located in Custom NPM UI Library catalog

I have recently developed an NPM package to store all of my UI components that I have created over the past few years. After uploading the package onto NPM, I encountered an issue when trying to use a button in another project. The error message "Module no ...

Tips for updating multiple bundled javascript files with webpack

I am working on a straightforward app that requires users to provide specific pieces of information in the following format. Kindly input your domain. User: www.google.com Please provide your vast URL. User: www.vast.xx.com Select a position: a) Bottom ...

Try to refrain from invoking effect within a component that is being conditionally rendered

I have a particular component that I am working with: const Component = () => { useEffect(() => { console.log('Executing useEffect in the Component') }, []) return <Text>element</Text>; } Whenever I conditionally re ...

Tips for incorporating a variable in a jQuery addClass method

Just starting out with jQuery and still learning. I'm attempting something seemingly simple, but struggling a bit. My goal is to customize a specific element by adding a variable in jQuery. I want to add the 'styler' class to a div with the ...

Manipulating a React table: Customizing a row in the table

Below is the code snippet: const [data, setData] = useState([ {id: 1, name: 'paper', qty: 10}, {id: 2, name: 'bottle', qty: 10}, ]); const [isEditable, setEditable] = useState([]); useEffect(()=>{ data.map(each=>{ ...

The button transforms once the user submits the form

I have two buttons labeled "Save" and "Saving..." <div ng-switch on="isLoading"> <div ng-switch-when="true"> <button type="button" class="btn btn-primary btn-block disabled">Saving ...</button> </div> <div ng-switch- ...

Tips for converting file byte code to file form data

From one folder I am retrieving a file and uploading it to another server. However, when I extract the file from the first folder, I receive a byte code representation of that file. The API for uploading the file to the second folder requires FormData as a ...

Is there a way to verify the presence of a value in an array?

Searching for a specific value in an array is my current task. Let's take the example of having an array of users, where I need to determine if a particular user is present in that array. The array looks like this: Array(5) 0:{id: "empty", name: "Ch ...

Is there a way to showcase the data of each table row within the tr tag in an Angular 8 application?

I have been developing an application using Angular 8. The employee-list component is responsible for presenting data in a table format. Within the employee-list.component.ts file, I have defined: import { Component } from '@angular/core'; impo ...

What is the best method for sending XML data to a URL using JavaScript within an Adobe AIR application?

I am currently developing an application that involves downloading an XML string from a URL and then posting it to another URL. I have managed to successfully download the XML string and can manipulate it using alerts, however, I am struggling with posting ...

I am looking to improve my form submission process by using JavaScript to only submit the form itself, rather than the

I have integrated JS and HTML code. The issue I am facing is that upon submission, the entire page is being submitted instead of just my form. function submit_by_id() { var name = document.getElementById("name").value; var email = document.getElementByI ...

Guide on integrating a JavaScript control (JavaScript package) obtained from GitHub into my asp.net application

Hello everyone, I am a newcomer to GitHub and have some basic questions to ask. Recently, I downloaded the package from https://github.com/jspreadsheet/ce in .zip format for using in my asp.net web application. However, I am not sure how to incorporate the ...

Using setInterval() does not automatically fetch JSON data at a specified interval for me

Attempting to constantly update the latitude and longitude coordinates from a dynamic API has proven to be a challenge. Despite utilizing jQuery with a set interval of 1000 milliseconds, the data retrieval from the API does not occur as expected. While i ...

Sending a volatile emit to a specific namespace using SocketIO

An issue is arising with the following code snippet, resulting in the TypeError: Cannot read property 'volatile' of undefined (in other words, map does not have a volatile emit method): io = require("socket.io").listen(server) map = io.of "/map" ...

Enhancing the session helper in Silex with additional values

Hey there, I'm currently working on a basic shopping cart using an MVC framework called Silex. However, I've run into a JavaScript/AJAX issue that I could use some help with. My problem arises when trying to add a product to the basket. The issue ...

Modifying the CSS properties of elements with identical IDs

Encountering an issue while attempting to modify the CSS property of elements with similar IDs using JavaScript. Currently, running a PHP loop through hidden elements with IDs such as imgstat_1, imgstat_2, and so forth. Here is the code snippet being emp ...