Breaking a string into separate parts using various layers of delimiters

I am currently facing an issue with this specific string:

{1 (Test)}{2 ({3 (A)}{4 (B)}{5 (C)})}{100 (AAA{101 (X){102 (Y)}{103 (Z)})}

My goal is to divide it using { as the initial delimiter and } as the final delimiter. However, there are nested brackets present in the string.

Is there a way for me to split this string so that it appears like this:

1 (Test)
2 ({3 (A)}{4 (B)}{5 (C)})
100 (AAA{101 (X){102 (Y)}{103 (Z)})

Furthermore, I will also need to perform another split within the nested brackets afterward.

Answer №1

To extract tokens and their corresponding depth level from a string, you can utilize the regular expression /([\{\}])/ to split the string into an array of tokens. By iterating through this array, you can determine the depth level of each token.

const inputString = "{1 (Test)}{2 ({3 (A)}{4 (B)}{5 (C)})}{100 (AAA{101 (X){102 (Y)}{103 (Z)})}";
let tokens = inputString.split(/([\{\}])/);
let results = [];
let depth = 0;

tokens.forEach(function analyzeToken(token) {
    if (!token) return;
    
    if (token === "{") {
        depth++;
        return;
    }
    
    if (token === "}") {
        depth--;
        return;
    }

    results.push({ depth: depth, token: token });
});

console.dir(results);

Answer №2

Below is the code snippet that can be used:

var text = '{1 (Test)}{2 ({3 (A)}{4 (B)}{5 (C)})}{100 (AAA{101 (X){102 (Y)}{103 (Z)})}';
var modifiedText = text.replace(/\{/g,'');
var finalText = modifiedText.replace(/\}/g,'\n')
console.log(finalText);

//Output

1 (Test)
2 (3 (A)
4 (B)
5 (C)
100 (AAA101 (X)
102 (Y)
103 (Z))

Answer №3

If you want to split the code into a multi-dimensional array, you can use the snippet provided below:

let string = '(another((checker)check)john)(smith)(jane(does(smith(kline))))';

function getArray(text) {
  if (Array.isArray(text)) return text.map(t => getArray(t));
  var flag = null,
    arr = text.split(/([\(\)])/).filter(t => t.trim()),
    result = [],
    temp = '',
    depth = 0,
    groups = [];
  if (arr.length <= 1) return text;
  
  for (let i = 0; i < arr.length; i++) {
    temp = arr[i];
    
    if (temp === '(') {
      if (flag === null) {
        if (result.length) groups.push(result.join(''));
        flag = depth;
        result = [];
      }
      depth++;
    }
    
    if (temp === ')') {
      depth--;
    }

    result.push(temp);
    
    if (flag !== null && flag === depth && temp === ')') {
      let fr = result.join('');
      
      if (fr === text && RegExp('^\\(').test(fr) && RegExp('\\)$').test(fr)) {
        let ntext = text.replace(/(^\(|\)$)/g, '');
        fr = getArray(ntext);
      }
      
      groups.push(fr);
      flag = null;
      result = [];
    }
  }
  
  if (result.length) groups.push(result.join(''));
  
  return groups.map(g => getArray(g));
}

let finalArr = getArray(string);
console.log(JSON.stringify(finalArr));

//Expected output: [[["another",[[["checker"],"check"]],"john"]],["smith"],[["jane",[["does",[["smith",["kline"]]]]]]]]

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

What is preventing me from using JavaScript to generate labels?

My current project involves creating dynamic input fields to filter products by color. I initially attempted static checkbox inputs for this purpose, which worked fine. Now, I want to achieve the same functionality but dynamically through JavaScript. Inste ...

Unordered calling of functions in JavaScript - is it possible?

I'm currently working on a project that involves extracting data from an SQL database and converting the output of a query (which is a number) into a corresponding color, which is then passed to a JavaScript variable. Essentially, I am using ajax to ...

Establishing a default v-on event for a Vue component

Within my custom 'text-input' components, I include some default markup and an 'input' element. An effective method for passing the value of the 'text-input' to its parent is by emitting an event when the value changes. To h ...

Encountering a 'DiscordAPIError: Unknown interaction' error while attempting to share details about a command

As I work on a slash command to deliver information about a specific command when users type /help, I encountered an error when trying to add multiple commands: E:\v13\node_modules\discord.js\src\rest\RequestHandler.js:298 ...

Module TypeScript could not be located

Currently, I am in the process of converting my nodejs project from JavaScript to TypeScript. I have updated the file extensions from .js to .ts, but now I am encountering errors with require(). In an attempt to fix this issue, I have added the following c ...

Using Node.js to import modules without the need for assignment

In my recent project, I decided to organize my express application by putting all of my routes in a separate file named routes.js: module.exports = function(server) { // Server represents the Express object server.get('/something', (req, res) ...

Guide on managing opening and closing of dialogs in a Vuetify data table

We have developed an application for a staffing agency that allows the Admin to view Users in a Vuetify data table. However, when displaying User Notes in the table, we encounter issues with long notes not fitting well within a table cell. Our goal is to i ...

Turning On/Off Input According to Selection (Using jQuery)

<select name="region" class="selection" id="region"> <option value="choice">Choice</option> <option value="another">Another</option> </select> <input type="text" name="territory" class="textfield" id="territo ...

Apply a style to the div element that contains a TextInput component

As a beginner in the world of React and Material UI, I am currently working with Material UI version "1.0.0-beta.17", React 15.6.2, styled-components 2.0.0, and styled-components-breakpoint 1.0.1. Within a div element, I have two TextInput fields. const ...

ASP.NET sending an AJAX request

Hi, I am new to the world of ajax requests and asp.net. I am facing an issue while sending an ajax request to an aspx page. Even though the server side debugging seems fine, I am encountering an error message in the response. I have already tried changing ...

Next.js server component allows for the modification of search parameters without causing a re-fetch of the data

I have a situation where I need to store form values in the URL to prevent data loss when the page is accidentally refreshed. Here's how I am currently handling it: // Form.tsx "use client" export default function Form(){ const pathname ...

Guide on implementing a check all and delete function using the datatables (jquery datagrid plugin)

I am currently utilizing the Datatables jQuery plugin to manage my table rows. While it comes with a tabletools plugin that allows for a checkall function, I am wondering how I can add a custom delete button and retrieve the selected row. Fortunately, I a ...

What is the most effective method for fetching images from MongoDB?

I'm currently working on a web application that uses MongoDB's GridFS to store and retrieve images. However, I'm facing an issue where retrieving images from the database takes significantly longer than expected when a user makes a request. ...

How to display an [object HTMLElement] using Angular

Imagine you have a dynamically created variable in HTML and you want to print it out with the new HTML syntax. However, you are unsure of how to do so. If you tried printing the variable directly in the HTML, it would simply display as text. This is the ...

Leveraging jQuery plugin within a React ecosystem

While utilizing semantic react, I found myself in need of a date picker. Fortunately, I stumbled upon this library: https://github.com/mdehoog/Semantic-UI-Calendar However, I am unsure how to incorporate it into my react-based project since it's not ...

Emphasize today's date on the w3widgets adaptable calendar

While developing a website featuring a calendar to showcase events, I came across w3widgets, which proved to be quite helpful. However, I encountered an issue when trying to highlight the current date on the calendar. It seems that the calendar only highli ...

Error: Unable to locate module: cannot find './node_modules/@material-ui/core/IconButton'

Encountering an error in the browser: Error: Failed to compile ./src/components/layout/search/Searchbar.js Module not found: Can't resolve './node_modules/@material-ui/core/IconButton' in 'C:\Users\Ja\Desktop\ ...

Error possible in modal due to interaction between JavaScript, PHP, and Bootstrap - Unable for PHP file to successfully retrieve value from JavaScript file

I have an existing database that is already populated. Additionally, I have a JavaScript function that captures the ID of the element when a button is pressed. Here's an example: Name of Subject | Actions -------------------------------------- ...

Tips for generating dynamic JSON: Organize the data by filtering it and creating key-value pairs for the appropriate JSON objects

How can I generate dynamic JSON based on input, filter data, and create appropriate key-value pairs for JSON objects? The database schema can be viewed https://i.sstatic.net/iP1JS.png Although I attempted the following code, it did not produce the desi ...

Cannot work on repl.it; it seems to be incompatible with the freeCodeCamp - JavaScript Algorithms and Data Structures Projects: Roman Numeral Converter

Recently completed my Roman Numeral Converter and it functions correctly on repl.it. However, when testing it on freecodecamp, the output displayed: // running tests convertToRoman(2) should return "II". convertToRoman(3) should return "III". ... // tests ...