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

The selected jquery script is failing to function as intended

I'm currently implementing jQuery chosen in a select element to enhance user experience, however I'm facing an issue when attempting to copy the chosen div to another div using jQuery $(document).ready(function() { $(".chosen").chosen({}); ...

When you call setTimeout from a static function, it does not get executed

Having a problem with starting a timer in my utility typescript class. The static function initTimer() uses setTimeout but when called from a react component, the timer doesn't start. StyleWrapper.tsx const StyleWrapper: FC = (props) => { cons ...

"Exploring Mocha and Chai: Tips for Generating a Comprehensive List of Errors in Test Cases

I am currently working on a unit test to validate a list of elements. Example: arr = [ { element : "aaa", validation : false }, { element: "bbbb", validation: true }, { element: "ccc", validation: false } While running my unit test, I encountered ...

My code seems to be malfunctioning - why can't I keep the aspect ratio?

UPDATE: Can someone please assist me with maintaining the aspect ratio of a drawn image? I am struggling to achieve this and would appreciate any help. I have been attempting to upload an image, draw it using the imageDraw() function, and fit it within a ...

Attempting to toggle variable to true upon click, but encountering unexpected behavior

On my webpage, I have implemented a simple tab system that is only displayed when the variable disable_function is set to false. However, I am facing an issue with setting disable_function to true at the end of the page using a trigger. When this trigger ...

Transitioning between modals using Tabler/Bootstrap components in a ReactJS environment

Currently, I am constructing a Tabler dashboard and incorporating some ReactJS components into it. Initially, I used traditional HTML pages along with Jinja2 templates. However, I have now started integrating ReactJS for certain components. I prefer not t ...

Waiting for a response from an API with the help of nodejs

I'm new to exploring Node.js and I'm interested in making API calls where the result is awaited before proceeding with any further actions. // defining endpoint function function getListMarket() { var deferred = Q.defer(); deferred.resolve(Q ...

Error: Unable to locate module - Invalid generator instance detected. The Asset Modules Plugin has been started with a generator object that does not adhere to the API standards

Encountering an issue in nextjs when utilizing the 'asset/inline' Asset Module Type within a custom webpack configuration while running yarn dev. I attempted to utilize the 'asset/inline' asset module type to output the URI of the impor ...

angularsjs state provider with multiple parameters

I am struggling to create a state provider that can handle multiple parameters. Is it possible to capture them as an object or array, or do I have to capture them as a string and then separate them? For example, this is my current provider: .state(' ...

I'm having trouble accessing my POST data using console.log. Instead of getting the expected data, all I see in the console when I try to GET is "

My code for the POST function is working, but when I try to retrieve and display the POST response from the server, all I get is "null". Can anyone help me figure out how to properly send data from my form to the server and then successfully console log it ...

Tips for managing this JavaScript JSON array

Here is an example of a JSON array: var data = { name: 'Mike', level: 1, children: [ { name: 'Susan', level: 2, }, { name: 'Jake', level: 2 }, { name: 'Roy', level: 2 }, ...

Creating nested tables by assigning unique Div IDs to each table element

Can we utilize a straightforward JavaScript/jQuery function to nest elements inside table elements? For instance, every square comes with its own unique ID (A1, B7, C5). How can I use this ID to insert the checker image in any selected tile upon clicking? ...

The Blueimp File Uploader seems to be sending numerous submissions at once

I've been tasked with fixing an issue on our site that I didn't originally build. The previous developer who worked on this project is now occupied with another task, leaving me to figure out what's going wrong. We are utilizing the basic bl ...

`Upkeeping service variable upon route alteration in Angular 2`

Utilizing a UI service to control the styling of elements on my webpage is essential. The members of this service change with each route, determining how the header and page will look. For example: If the headerStyle member of the service is set to dark ...

How to extract data from Facebook's JSON using Javascript

I am utilizing a JavaScript API to extract Facebook comments. After receiving the JSON result below, I'm wondering how I can unpack and utilize them on my webpage? { "id": "1234567891_2823098717038_3160191", "from": { "name": "U ...

Tips for extracting dynamically loaded content from a website using Node.js and Selenium?

I'm currently encountering some challenges when trying to scrape a website that utilizes react for certain parts of its content, and I'm unsure about the reason behind my inability to extract the data. Below is the HTML structure of the website: ...

The Axios.catch method does not handle network or console errors

Utilizing React with axios and redux-promise poses a challenge when it comes to handling 404 errors. See the example below: This is the snippet of code causing the issue: const url = FIVE_DAY_FORECAST_URL.replace("{0}", city); axios.interceptors.resp ...

Error is thrown when attempting to access nested elements using GetElementsByClassName within the window.onload function

I have a funky looking table on my webpage, here's an example: <body> <table class="table table-bordered"> <thead> <tr> <th>#</th> <th>Product name</th> <th>Product ...

React-native - Dropdownpicker - Error: Unable to retrieve label for selected choice

I'm encountering an issue with DropDownPicker in my react-native project during page load Here is the code snippet where I am using DropDownPicker: <DropDownPicker items={[ { la ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...