Technique for converting a String into an Array

Is there a way to convert a string in the format:

"I (get (it)) not"

into an array structure like this:

['I', ['get' , ['it']], 'not']

I'm looking to use parentheses as "levels" within the array. I have a good understanding of JavaScript, but I'm struggling to figure out how to accomplish this task. I've spent 3 hours attempting different approaches, but I haven't been successful yet.

Answer №1

Feeling a bit generous today, here's a unique example I came up with just for you:

// This function takes a string and converts it into an array representing the grouping symbols in the string
function parseString(str)
{  
   // Trim any leading or trailing whitespace from the input string
   str = str.trim();
   
   // Split the string into an array of individual characters
   var arr = str.split('');
   
   // Initialize an array to store matched parts of the string
   var parsed = [];
   
   // Keep track of the current level of parenthesis nesting
   var parentheses = 0;
   
   // Create an array to represent each level of parentheses
   var levels = [parsed];
   
   // Shortcut to access the array for the current parentheses level
   var current = parsed;
   
   // Filter out any operators not intended for checks
   var notOperators = /^[ ()]*(.*?)[ ()]*$/;
   
   // Count occurrences of a substring in the string
   function count(arg, substring) { return arg.split(substring).length; };

   // Check if there are an equal number of opening and closing parentheses
   if (count(str, '(') !== count(str, ')')) throw new SyntaxError('Unmatched parentheses');

   // Add the word before an operator/space, if applicable
   function addPart()
   {  
      // Remove already parsed parts and get the word
      var beginning = arr.splice(0, i).join('').trim();
      
      // Remove any operator tokens
      var str = beginning.match(notOperators)[1];
      if (str) current.push(str);
      
      // Reset the loop counter after parsing a part of the string
      i = 0;
   }

   // Loop through each character in the input string
   for (var i = 0; i < arr.length; ++i)
   {  
      var token = arr[i];
      
      // Handle spaces between words
      if (token === ' ') addPart();
      
      // Open a new grouping symbol
      else if (token === '(')
      {  
         addPart();
         
         // Add a new level of hierarchy and update the reference
         current.push([]);
         current = levels[++parentheses] = current[current.length - 1];
      }
      
      // Close an open grouping symbol
      else if (token === ')')
      {  
         addPart();
         
         // Move one level up the hierarchy of parentheses
         current = levels[--parentheses];
      }

      // Ensure no invalid instances like "a)(" are present
      if (parentheses < 0) throw new SyntaxError('Unexpected token )');
   }

   // Add the final word before the end of the string
   addPart();

   // Return the array that represents the string
   return parsed;
}

Just for your clarity, consider this example:

parseString('The (quick) brown (fox (jumps)) (over the) lazy (dog)');

This will output:

["The", ["quick"], "brown", ["fox", ["jumps"]], ["over", "the"], "lazy", ["dog"]]

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

Changing the boolean value within a nested array using Mongoose

I am struggling with updating the boolean value of flagged comments in a Schema that holds an array of objects for comments. I have attempted to use updateOne and aggregate methods, as well as $elemMatch, but so far, none of them have worked. Additionally, ...

Does Java Generics Allow Instantiating Arrays with Parameterized Types?

It seems I may be misunderstanding something here. From what I've read, it's widely stated that arrays of parameterized types are considered illegal in generics. Take for example the snippet from AngelikaLanger: static void test() { Pair&l ...

Can a single Axios request in JavaScript include both a Body and Files?

Is it possible to send both a file and body with the POST request below in axios? axios.post("http://localhost:3000/upload", formData) How can I include something in the body:{} section as well? Server response: files: { myFile: { nam ...

Embed a JavaScript file containing PHP code

Recently, I incorporated PHP into my JavaScript code, as shown below: var currentTotalContribution = <?php echo $myContribution; ?>; Now, I am interested in moving that content to my JavaScript file and importing it. I am unsure if this is achievab ...

Locate records that meet criteria in various fields within a nested array in MongoDB

Suppose I have an array of objects (let's call it array A) and I am looking for a way to query MongoDB to find documents where one field matches a property in object 1 from array A, and another field matches a different property in the same object. N ...

What is the best way to prioritize one external stylesheet over another?

Is there a way to ensure that an external stylesheet takes precedence over conflicting styles? I am looking to include a link to a stylesheet that will change the color scheme of a page, but have had trouble with other styles interfering. I attempted appen ...

Storing a multidimensional array in a database using a foreach loop

I created a script to extract prices and names from a website using a foreach loop. foreach ($table_rows as $tr) { // for each row $row = $tr->childNodes; if ($row->item(0)->tagName != 'tblhead') { // avoiding headers $d ...

It appears that combining Object.assign with Function.prototype may not function as expected

Currently attempting to develop a mixin for a sophisticated feature within a library. My initial approach was successful: const proto = Object.create(Function.prototype); However, I now face the challenge of implementing multiple inheritance where an ob ...

React timer slide show malfunctioning

While I have some experience with React, I'm struggling with a seemingly simple problem that I just can't figure out. My goal is to cycle through an array of images and display the image at the current index. The console logs show the correct in ...

Is there a way to ensure that functions operate effectively within a modal window?

While working on a script for my job, I decided to move most of my HTML content into a modal halfway through writing the code. The challenge now is that many functions I've already created no longer work with the content inside the modal. I'm hop ...

What is the method for inserting a button into an ejs file with javascript?

I have a small list with 8 to 10 elements at most and I am looking to dynamically add buttons on an ejs page based on the number of items in the list. For example, if my list is ["Salad", "Tomato", "Paste"], then 3 buttons should be generated on the page a ...

Is it possible to define a constant enum within a TypeScript class?

I am looking for a way to statically set an enum on my TypeScript class and be able to reference it both internally and externally by exporting the class. As I am new to TypeScript, I am unsure of the correct syntax for this. Below is some pseudo-code (whi ...

Exploring Java 14: Records and Arrays

Consider the code snippet below: public static void main(String[] args) { record Foo(int[] ints){} var ints = new int[]{1, 2}; var foo = new Foo(ints); System.out.println(foo); // Foo[ints=[I@6433a2] System.out.println(new Foo(new int ...

Encounter an issue while trying to fetch a JavaScript value from a variable using Selenium with Python

Looking to extract the value of the variable remainingTimeString from this specific webpage using Python and Selenium webdriver. I am attempting to utilize the driver.execute_script() function in my code snippet below: import selenium.webdriver options = ...

Ionic: How come my image is not loading with HTTP.GET?

I have been attempting to populate a gallery in my Ionic application by fetching images from a JSON file, but I am encountering issues. While following a guide on creating a grid-like image gallery using the Ionic framework (https://blog.nraboy.com/2015/03 ...

I am facing a challenge in retrieving a response from the jQuery AJAX Success function

Hey everyone, I'm currently working on an application that requires me to obtain the server time before sending out AJAX requests. The challenge lies in accessing the server time by making a request through AJAX. Here's the code snippet within my ...

Adjust the top margin of a div to match the height of the screen within an iframe, ensuring cross-browser

Trying to adjust the margin-top of a div to 100% of screen height within an iframe seems to be causing issues with jQuery, as it either returns 0 or inaccurate values. While CSS3's 100vh can work as an alternative, it may not be supported in older an ...

Make text come to life as the user scrolls across a fixed positioned div

As the user scrolls, I am attempting to animate four headings. First, I create a sticky positioned div. Then, as the user scrolls over the headings, each one toggles the class .active sequentially, with the last one remaining visible and the scrolling cont ...

Will Angular 2 be taking over from traditional AngularJS or will it simply provide another option?

Considering the shift from Angular 1's MVC architecture to Angular 2's component-based structure, it seems like migrating between these versions would necessitate a significant amount of refactoring. Unless there are unforeseen factors at play? ...

What is the best way to show a pop-up model at the bottom of a webpage?

I am working on a project that involves a popup modal that needs to appear after 10 seconds. However, the issue I am facing is that the modal is currently displaying at the top of the page, but I would like it to be shown at the bottom of the page just abo ...