Markdown - shorthand tables

From: Peter (BOUGHTONP)12 Jun 2011 23:20
To: af (CAER) 7 of 7
Heh, the original is in Java, and can't be directly translated because JS doesn't have equivalents.

Although... it does have replace callbacks which Java doesn't, so could actually be an interesting comparison...

Here we go:

java code:
private String convertTables( String html )
{
   Pattern p = Pattern.compile("(?ms)^<p>!table(.*?)(?<=\\n\\s{0,99})/table</p>", 0);
   Matcher m = p.matcher(html);
   StringBuffer sb = new StringBuffer("");
 
   while (m.find())
   {
      String[] Rows = m.group(1).trim().split("(?:^|\\]?\\n)\\s*\\[");
 
      String Head = "<thead><tr><th>"
         + Rows[1]
              .replaceAll("\\|","<th>")
              .replaceAll("\\]\\s*+$","</th>")
         + "</thead>"
         ;
 
      String Body = "<tbody>";
 
      for ( int i = 2 ; i < Rows.length; i++ )
      {
         Body += "<tr><td>"
            + Rows[i]
            .replaceAll("\\|","<td>")
            .replaceAll("\\]\\s*+$","</td>")
            ;
      }
 
      m.appendReplacement(sb,"<table>" + Head + Body + "</tbody></table>");
   }
 
   m.appendTail(sb);
 
   return sb.toString();
}



javascript code:
function convertTables( html )
{
   return html.replace
      ( /^<p>!table([\w\W]*?)\/table<\/p>/gm
      , function()
         {
            var Rows = arguments[1].split(/(?:^|\]?\n)\s*\[/);
 
            var Head = '<thead><tr><th>'
               + Rows[1]
                    .replace(/\|/g,'<th>')
                    .replace(/\]\s*$/g,'</th>')
               + '</thead>'
               ;
 
            var Body = '<tbody>'
 
            for ( var i = 2 ; i < Rows.length; i++ )
            {
               Body += '<tr><td>'
                  + Rows[i]
                  .replace(/\|/g,'<td>')
                  .replace(/\]\s*$/g,'</td>')
                  ;
            }
 
            return '<table>' + Head + Body + '</tbody></table>'
 
         }
      )
}



Of course, the JS one is just as flaky as the original, but if you do feel like doing anything with it, go ahead. :)