Transform markdown into HTML code

Is there a way to effectively transform a string that resembles the following format:

'* [-]Tree Item1',
'** [-]Tree Item1-1',
'*** Tree Item1-1-1',
'*** Tree Item1-1-2',
'*** Tree Item1-1-3',
'** Tree Item1-2',
'*** Tree Item1-2-1',
'** Tree Item1-3',
'* Tree Item2',
'** [-]Tree Item2-1',
'*** Tree Item2-1-1',
'**** Tree Item2-1-1-1',
'* Tree Item3'

into an HTML unordered list structured like this:

<ul>
   <li>
      Tree Item1
      <ul>
         <li>Tree Item1-1</li>
         ...
      <ul>
   </li>
   <li>
      Tree Item2
      <ul>
         <li>Tree Item2-1</li>
         ...
      <ul>
   </li>
   ...
</ul>

If you have suggestions or solutions, they would be greatly appreciated.

PS: Markdown libraries are not an option for my specific needs. I am looking for an algorithm that can accomplish this task.

Answer №1

When it comes to handling code, Stack Overflow relies on PageDown, a tool that is likely to suit your requirements.

Answer №2

Utilizing a markdown library may have been excessive and not a viable option in this scenario. However, I have managed to devise a solution that appears adequate for the time being...

Essentially, the string resembling markdown is initially split into an array. Subsequently, for each element within the array, the depth and text details are computed, which are then used to construct a nested array. The process goes something like this;

var arrList = str.split(','), //where str includes markdown-style string from the query provided above 
    nestedArray = [];

Array.forEach(arrList, function (item) {
   var nodeData = this.getNodeDataFromString(item);                
   //establishing a nested array based on level/text information obtained for each item,
   nestedArray.push(someWorkedOutData(nodeData));
}

function getNodeDataFromString () {
   var matches = str.match(/\*/g),
        retVal = {
            level: matches.length - 1
        },
        regex;

    regex = new RegExp('^\\' + matches.join('\\') + ' (.*)');
    str.replace(regex, function (match, p1) {
        retVal.text = p1;
    });
    return retVal;
}

The resultant nested array is then employed to create the HTML markup through a recursive function.

View the functional solution here (The solution has been crafted using the ExtJS library as I am currently working with it).

Any comments or critiques would be greatly appreciated.

Thank you,

C.

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

Creating a hierarchical list structure from a one-dimensional list using parent and child relationships in JavaScript

I am in the process of developing a web application that requires handling nested geographical data for display in a treeview and search functionality. The initial raw data structure resembles this: id:1, name:UK id:2: name: South-East, parentId: 1 id:3: ...

Problems with form functionality in React component using Material UI

Trying to set up a signup form for a web-app and encountering some issues. Using hooks in a function to render the signup page, which is routed from the login page. Currently, everything works fine when returning HTML directly from the function (signup), ...

the dropdown menu toggle is not working as expected

My dropdown icon is not appearing and the menu options are not functioning properly. Despite trying to use a script to display the text when an option is clicked, it doesn't seem to be working. It appears that the toggle functionality is not working ...

Vuetify offers a convenient solution for implementing multiple buttons in a Vue

My search bar retrieves data from an API query in the following format: Data: [[id, datafield1, datafield2],[id, datafield1, datafield2],...] I wish to include an on/off button for each row of the data, with each button having its own independent state. ...

`javascript pop up notification will only display one time`

I am currently developing a chrome extension with two different modes. When the user clicks on the icon, a pop-up message should appear to indicate which mode is active. However, I am facing an issue where the message does not always display when the pop- ...

What is the best way to reference an i18n entry within .json files?

I am in the process of creating a user interface using SAP UI5 and my goal is to make all text elements internationalized. Below is a snippet of my view in .xml format where I successfully retrieve text in different languages using placeholders enclosed i ...

I need to mass upload a collection of resumes stored in a zip file, then extract and display the content of each resume using a combination of HTML

I recently used a service to extract and retrieve the contents of a zip file. I am trying to read the content of the files and integrate them into the scope of my Angular project. Any suggestions would be greatly appreciated. Below is an outline of my func ...

Experience the impact of a lagging network connection on Chrome extensions through the power of React-NextJS

I'm currently working on a Chrome extension that requires me to limit download speeds in the browser programmatically (client-side). Despite researching extensively on the subject, I have not been able to find any information on how to achieve this us ...

Guide for populating the chosen item in a combobox when the form control option has various parameters

I need help populating the selected saved item into the form control. <select class="form-control"> <option data-parameter-id="685" data-parent-id="1052" data-aggregation-id="null" data-aggregation-parameter="null">ABC</option> & ...

How to efficiently eliminate multiple entries with SREM in ioredis?

I am curious about the proper syntax for removing multiple entries using the SREM command. When I try this: const myKey = "myKey"; const entriesToRemove: string[] = ... this.redisClient.srem(myKey, entriesToRemove); I end up with: ReplyError: ...

What is causing this code to break when using ajax's `data` parameter?

I'm relatively new to JavaScript, and I've been working on some code that seems to be properly formatted. However, whenever I add the data elements, it breaks the code. I've checked the jQuery documentation and as far as I can tell, I'm ...

Transferring information between AngularJS and Express/Node without using AJAX

My application is built using AngularJS on a node/express backend, with user authentication handled by passport. After a user signs in or signs up, the communication between my Angular controllers and express is done through $http ajax/xhr calls. The form ...

The loss of Webgl context that remains unrecovered

I am facing an issue with the loss and restoration of webgl context. My application is quite complex, containing a lot of data, graphs, lists, and maps. Within the map section, I utilize webGL to ensure optimal performance. My code effectively manages th ...

Allow the javascript callback function to complete before proceeding

Utilizing the Google Storage API, I am saving a file in a GCP bucket within an asynchronous function. My objective is to wait until I receive an error or success callback before proceeding with the subsequent lines of code. However, I am encountering the i ...

Is there a way to send all the results of a Flask database query to a template in a way that jQuery can also access

I am currently exploring how to retrieve all data passed to a template from a jQuery function by accessing Flask's DB query. I have a database table with customer names and phone numbers, which I pass to the template using Flask's view method "db ...

Using both Ajax and a standard submit can be applied to a single form in jQuery

I need to implement a confirm step on one of my pages. Here's what I want to achieve: When the user clicks 'submit', an AJAX request is triggered, which performs the necessary action and then displays a confirmation dialog If the user ...

Programming the tab pages within Chrome

By using JavaScript, I successfully opened a new tab at www.blogger.com from the Main.html page. <script> window.open("https://www.blogger.com"); </script> I am now on the blogger page. My goal is to automatically scroll to the end of the bl ...

Notification pop-up for accepting cookies on a website

I am curious about how to insert a .js code into a button within a bootstrap alert so that when the user clicks 'accept', the alert box does not reappear. Thank you very much. Here is the code I have, but it is not working. Javascript: $(".bt ...

What is the correct RegEx pattern I should use to properly match the provided test case without including the ending period?

Regular Expression: /@([\S]*?(?=\s)(?!\. ))/g Given String: 'this string has @var.thing.me two strings to be @var. replaced'.replace(/@([\S]*?(?=\s)(?!\. ))/g,function(){return '7';}) Expected Result: ...

Issues with debuggers in Chrome and Firefox with AngularJS are causing frustration for developers

Currently, I am in the process of developing a hybrid application that combines AngularJS with Angular 8. As part of my testing procedure, I am attempting to debug the application. However, I have encountered an issue where the debuggers function properly ...