Braj
Braj

Reputation: 46871

Javascript regex to create nested html list item

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.

Upvotes: 0

Views: 195

Answers (1)

Dan Prince
Dan Prince

Reputation: 29999

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.

Upvotes: 1

Related Questions