reverbnation reverbnation - 5 months ago 47
Javascript Question

How to replace and convert # list to html ul list Javascript regex

How to string#replace using regex to convert the following

# title 1
# title 2
# title 3


to

<ul>
<li>title 1</li>
<li>title 2</li>
<li>title 3</li>
</ul>

Answer

You can do it with two String#replace method

var div = document.getElementById('content');
div.innerHTML = div.innerHTML
  // wrap all elements with ul
  .replace(/(((?:^|\n)\s*)[\*#](.*))+/g, '<ul>$&\n</ul>')
  // wrap all line with li
  .replace(/((?:<ul>\n?|\n)\s*)[\*#](.*)/g, '$1<li>$2</li>');
<div id="content">
  # title 1
  # title 2
  # title 3
</div>