0

Markdown

# Rahul
The community is here to help you with specific coding, algorithm, or language problems.The community is here to help you with specific coding, algorithm, or language problems.

## This is second heading
The community is here to help you with specific coding, algorithm, or language problems.

### This is third heading
The community is here to help you with specific coding, algorithm, or language problems.The community is here to help you with specific coding, algorithm, or language problems.

## This is fourth heading.

Desired output

<ol>
    <li>Rahul</li>
    <ol>
        <li>This is second heading</li>
        <ol>
            <li>This is third heading</li>
        </ol>
        <li>This is fourth heading</li>
    </ol>
</ol>

I have searched over the internet and stackoverflow too, but i was not able to get any useful information, no good learning resourses,etc.

Thanks for the help

Rahul
  • 1,858
  • 1
  • 12
  • 33

2 Answers2

0

To get you started, here's a quick regex technique to extract the headings.

markdown = `# Rahul
The community is here to help you with specific coding, algorithm, or language problems.The community is here to help you with specific coding, algorithm, or language problems.

## This is second heading
The community is here to help you with specific coding, algorithm, or language problems.

### This is third heading
The community is here to help you with specific coding, algorithm, or language problems.The community is here to help you with specific coding, algorithm, or language problems.

## This is fourth heading.`;

headings = ( markdown + '\n').match(/(#+ .*\n)/g);
console.log( headings )

The next steps will involve walking the list, and determining ...

  • if the next heading has more #'s, then add <ol>'s
  • or if the next heading has less #'s, then add </ol>'s

Note that if the next heading drops, for example, from 3 #'s to 1 #, there'll be a need to add 2 </ol>'s.

Trentium
  • 3,419
  • 2
  • 12
  • 19
0

Well, that was an interesting exercise. My code is too long to post, but you can view it here..

Essentially:

I created a 4 layers deep sample markdown text.

Converted it to html.

Imported the html into a temporary DOM.

Used one of the getElementsBy methods to collect all the headers in the temporary doc. To maintain document order for the h* elements, I pushed them and their text nodes into two arrays.

The next step is sometimes very much frowned upon by some people who consider it a bad programming practice, but I have used it numerous times without any problem and find it easier to handle then the alternatives: create a new html string by iterating through the arrays and surrounding each of the elements by the appropriate string representation of the necessary tag.

Finally, imported the tag into the main DOM.

It may not be 100% of what you need, but should get you close.

Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45