Is there a way to divide a string by using square brackets at the first level?

Here is a sample string:

key[type=order][0].item[id={getVal(obj[type=item][0].id)}]

I am looking to split this string into the following format:

 [
     ['key', '[type=order]', '[0]'],
     ['item', '[id={getVal(obj[type=item][0].id)}]']
 ]

Initially, I divide the string by the first level dot:

const str = 'key[type=order][0].item[id={getVal(obj[type=item][0].id)}]';
const arr = str.split(/\.(?![^[]*])/).filter(Boolean);

This results in an array like so:

['key[type=order][0]', 'item[id={getVal(obj[type=item][0].id)}]']

Next, I aim to split each item of the array using the first level square brackets:

arr.map(item => item.split(/(\[.+?\])/).filter(Boolean))

Which produces an array as follows:

[
    ['key', '[type=order]', '[0]'],
    ['item', '[id={getVal(obj[type=item]', '[0]', '.id)}]']
]

I intend to split the items only based on the first level square brackets without delving into nested ones. How can I achieve this using regex in JavaScript?

Answer №1

Make sure to include this code in your final split

arr.map(item => item.split(/(\[[^\]]+\(.*\).*\])|(\[.+?\])/).filter(Boolean))

This code will result in the following array:

[
    ['key', '[type=order]', '[0]'],
    ['item', '[id={getVal(obj[type=item][0].id)}]']
]

The regular expression used is /(\[[^\]]+\(.*\).*\])|(\[.+?\])/. The first part of the regex looks for square brackets with parentheses inside, while discounting any square brackets within them. The original regex continues after the |.

Update

arr.map(item => item.split(/(\[[^\]]+\([^\)]*\)[^\]]*\])|(\[.+?\])/).filter(Boolean))

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

ng-show directive in AngularJS is not functioning properly when utilized with CLI

After setting up my Angular app with ng new app, I attempted to hide certain elements conditionally using ng-show. Unfortunately, it doesn't seem to be working as expected. <span ng-show="false">Angular App</span> Regardless ...

issue with data binding in ons-dialog

Utilizing an ons-dialog to display a popup prompting the user to sign up for a newsletter. I have set a 3-second timeout to prevent users from immediately closing the prompt without reading it or waiting. I aim to initially show the dialog with the ' ...

JavaScript code to always keep the element on top of the page: "Make

I have developed a straightforward chrome extension tool that displays a small text message (a div with z-index 999999) on the webpage that the user is currently viewing. However, I am facing a problem where the div sometimes gets hidden beneath the existi ...

Tell apart the scrolling that users start themselves from the scrolling that is triggered by the browser when a page is first loaded

Can anyone help me figure out how to detect when a user first starts scrolling on my page, rather than the automatic browser-initiated scrolling that occurs on page reload? I've tried capturing the window's initial scroll position and using a ...

Javascript AppendChild Problem with Internet Explorer

When it comes to this particular snippet of code, everything seems to run smoothly in Firefox and Chrome. However, Internet Explorer is causing some major headaches. var anotherDiv= document.getElementById("anotherDiv"); var destination = document.getElem ...

Utilizing ckeditor's extraAllowedContent attribute for the viewhelper functionality

Is it possible to incorporate content for my php FormViewHelper method? The syntax is @form('inputName')@, which assigns a value to the input field if provided and the form has not been successfully submitted yet. I am developing a specialized ...

What is the process by which React recreates the React element tree (virtual DOM) with every state update?

From what I've gathered, every time a state is updated in React, it generates the react element tree (virtual DOM) and then compares it with the new one using a diffing algorithm. However, there's something I find puzzling. Let's say we hav ...

When working with GWT, you can easily attach an event listener to any element on the host page

I am looking to implement a MouseOver event handler for any tag, specifically targeting anchor tags in a legacy HTML page. Following a GWT guide, I successfully utilized their JSNI method to retrieve all anchor tags with some minor adjustments for errors. ...

Anticipating the execution of JavaScript code to finish

Below is the code snippet in question: var dataToSend2; // spawn new child process to call the python script const ls = spawn("python", ["./readDirectory.py"]); // collect data from script ls.stdout.on("data", function (info) { console.log("Pipe data ...

Tips for organizing an array of objects in JavaScript according to a specific attribute value?

I'm trying to sort an array of notification objects in decreasing order of severity: Error > Warning > Information. For example: var notificationArray = [ { code : "103", severity : "Error" }, { code : "104", severity : "Inform ...

Managing DateTime Arrays with Get and Set in C#

Can someone confirm whether the following code is compliant with C# rules? public DateTime[] datetime = new DateTime[]; I am unable to use get; set with this declaration. Furthermore, I need to save dates to datetime. Can anyone provide guidance on how ...

What mistake am I making while attempting to load this JavaScript array?

Adding another question related to what I believe is the issue here, but providing more detailed information can be beneficial. Here's my code: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content= ...

Reposition div when clicked

I have encountered a challenge where I am unable to perform a small task. My goal is to have the position of "div1" change upon clicking on "div2", taking into account that "div2" is nested inside "div1". Additionally, when clicking on "div2" again, "div1" ...

The functions that have been imported are not defined

I encountered a Error in created hook: "TypeError: _api__WEBPACK_IMPORTED_MODULE_0__.default.$_playerApi_getPlayers is not a function" issue while using Webpack through Vue CLI on my webpage. Below is the structure of my project directory: . + main.js + ...

What could be the reason for the absence of elements in the array

I am currently working on the task of transforming a csv file into an HTML table. The initial step involves extracting all the time cells from the csv file and storing them in a time array, as well as saving event cells to an events array and location cell ...

Updating or inserting bulk data using an Ajax proxy with CRUD operations

While implementing a bulk update/insert feature using an ajax proxy, I ran into an issue with store.sync(). This method sends a request to the server for each dirty record. But if there is an error with any of the records on the server, how can I properl ...

Have the functionality of right clicking and selecting Paste work in the input field using style=text and a button

Here is the code I am using: <script type="text/javascript"> $(document).ready(function() { $('#submit').prop('disabled', true); $('#links').change(function() { $('#submit').prop('disabled ...

Does the directive lack access to transcluded elements?

I seem to be missing something here, as I can't seem to get the desired outcome with my code: http://plnkr.co/edit/Qe2IzMMMR5BJZJpwkx9e?p=preview My goal is to create a directive that can be applied to a top-level <nav> element, and then manipu ...

JS: When the 'less than' operator falls short

I am facing an issue with a script that sends an AJAX request every 10 seconds (technically 11) to the user. I have created a simple countdown from 10 to 0 that repeats continuously. The countit function is triggered after each AJAX request to reset the c ...

Center align your animations without using the text-align property

I'm in the process of refining this custom animation to make it smoother. Check out the live animation here. The issue I'm encountering is that during the transition when the city name rotates up and replaces the old one, the text-align center ...