code: function matchClosing(input, tagname, html) {
    var closeTag = '</' + tagname + '>',
        openTag  = new RegExp('< *' + tagname + '( *|>)', 'g'),
        closeCount = 0,
        openCount = -1,
        from, to, chunk
        ;
  
    from = html.search(input);
    to = from;
  
    while(to > -1 && closeCount !== openCount) {
      to = html.indexOf(closeTag, to);
      if (to > -1) {
        to += tagname.length + 3;
        closeCount ++;
        chunk = html.slice(from, to);
        openCount = chunk.match(openTag).length;
      }
    }
    if (to === -1) {
      throw new Error('Unmatched tag ' + tagname + ' in ' + html)
    }
  
    return chunk;
  }
docs: Matches a closing tag to a open tag