Q:

Wrapping list item tags  with an  tag

I'm trying to build a tool that marks up text with HTML without the need to do it manually.  
Currently the tool takes text copied into a rich text editor and outputs the HTML after a bunch of .replace regex patterns are used to clean up some common issues.
One issue I cannot seem to solve is converting lists as it's pasted from MS word. Here's what it looks like from MS word:
<p>·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Lorem Ipsum dolores.</p>
<p>·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Lorem Ipsum dolores.</p>
<p>·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Lorem Ipsum dolores.</p>
<p>·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Lorem Ipsum dolores.</p>

I was able to convert this, via regex, so that each is wrapped with a list item, but I cannot figure out how to wrap the list items in unordered list tags.
For example, I'd like to change
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>

into
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>

I can't get the regular expression to match. Here's what I'm using:
.replace(/(?<!<\/li>)<li>/, "<ul><li>")

A:

RegExps with HTML is typically a bad idea. I personally would use DOMParser and alter the HTML with DOM methods. If you have only one one group of lis, it is as simple as selecting and appending them to a UL.

var str = `
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
`
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html')
var body = doc.querySelector('body')
var lis = doc.querySelectorAll('li')
var ul = document.createElement('ul')
body.insertBefore(ul, lis[0])
lis.forEach(li => ul.appendChild(li))
console.log(doc.querySelector('body').innerHTML)

If there can be more than one list, you need to find the groupings and add multiple uls.

var str = `
<li></li>
<li></li>
<p></p>
<li></li>
<li></li>
<li></li>
<p></p>
<li></li>
`
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html')
var body = doc.querySelector('body')
var lis = doc.querySelectorAll('li')
var groups = Array.from(lis).reduce((groups, li, index, arr) => {
  if (index === 0 || li.previousElementSibling !== arr[index-1]) {
    groups.push([])
  }
  groups[groups.length-1].push(li)
  return groups
}, [])
groups.forEach(lis => {
  var ul = document.createElement('ul')
  body.insertBefore(ul, lis[0])
  lis.forEach(li => ul.appendChild(li))
})
console.log(doc.querySelector('body').innerHTML)

