title: Parse Markdown headings to generate a nested list in JavaScript
body: <p>I've been trying to nest headings based on the number of "#". I parsed markdown and extracted all the headings. They're in following format</p>
  
  <pre><code># Getting Started
  # Heading 1
  ## SubHeading 1
  ## SubHeading 2
  ### SubSubHeading 1
  ### SubSubHeading 2
  #### SubSubSubHeading 1
  ## SubHeading 3
  </code></pre>
  
  <p>I tried to recursively convert it to a nested ul list but it doesn't seem to work.. This is what i did so far</p>
  
  <pre><code>function createRepresentationFromHeadings(headings, index, level) {
      var data = "&lt;ul&gt;";
      for (var i = index; i &lt; headings.length; i++) {
          var heading = headings[i];
          var parts = heading.split("# ");
          parts[0] = parts[0] + "#";
          data += "&lt;li&gt;" + parts[1];
          if (i + 1 &lt; headings.length) {
              var nextParts = headings[i + 1].split("# ");
              nextParts[0] = nextParts[0] + "#";
              if (determineHeadingLevel(nextParts[0]) &gt; level)
                  createRepresentationFromHeadings(headings, i + 1, determineHeadingLevel(nextParts[0]));
          }
          data += "&lt;/li&gt;";
      }
      data += "&lt;/ul&gt;";
      return data;
  }
  
  function determineHeadingLevel(part) {
      return part.length;
  }
  </code></pre>
  
  <p>It just creates a flattened ul. Here's a fiddle: <a href="https://jsfiddle.net/vrt2889q/" rel="nofollow noreferrer">https://jsfiddle.net/vrt2889q/</a></p>