0

I want to achieve the same functionality that is available on StackOverflow to convert below format into ul and li.

Sample input:

- a
 - b
 - c
- d

Expected output:

<ul>
   <li>
       a
       <ul>
          <li>b</li>
          <li>c</li>
       </ul>
   </li>
   <li>d</li>
</ul>

Is it possible with JavaScript regex?

What I have tried?

function convertToList(text) {
    return text.replace(/((?:^(- ).*$\r?\n*)*^(- ).*$)/gm, function($0, $1) {
        return '<ul>' + $1.replace(/^(- )(.*)$/gm, '<li>$2</li>') + '</ul>';
    });
}

but it doesn't work for nested list items.

Braj
  • 46,415
  • 5
  • 60
  • 76

1 Answers1

1

If you want to accurately recreate the functionality from this site, then I would look at using a markdown library.

Making parsers with Regex can be dangerous.

Community
  • 1
  • 1
Dan Prince
  • 29,491
  • 13
  • 89
  • 120
  • 1
    I found one more mark down library [showdown-highlight](http://softwaremaniacs.org/playground/showdown-highlight/) that can make my life easier. – Braj Apr 12 '15 at 09:48