Regexp that convert markdown tables to textile ones

410 views Asked by At

I'd like to convert markdown tables in textile one.

Markdown tables follow this pattern:

| column | column |
|--------|--------|
|        |        |

While textile this one:

|_.column |_.column |
|         |         |

Now I wrote the following expression:

text.gsub(/\|[-|]+/, '')

That remove the |--------| bars. I'd like also to add the _. before every column title, in order to make them bold.

Do you have any idea for obtaining this result?

2

There are 2 answers

0
cFreed On BEST ANSWER

I don't know ruby at all, hence can't be sure of anything about its own syntaxic aspects. So here is a Javascript proposed solution, hopefully it's known widely enough to be easily transposed:

function markdown2textileTables(source) {
  var lines = source.split('\n');
  lines.forEach(function(line, index, lines) {
    if (!!line.match(/^\|(?:[-]+\|)+$/)) {
      var prevLineCols = lines[index - 1].split('|');
      prevLineCols = prevLineCols.map(function(col) {
        return !!col ? '_.' + col.trim() : col;
      });
      lines[index - 1] = prevLineCols.join('|');
      lines.splice(index, 1);
    }
  });
  return lines.join('\n');
}

Working example here.

Note that I didn't take care of title columns length when changing from | column | to |_.column|, because I don't know if it matters or not.
If yes, the above code would need to be improved at the return !!col ? '_.' + col.trim() : col; statement, depending on current col.length and either adding spaces or cutting title.

0
scoa On

You could use pandoc:

pandoc mytable.md -t textile -o mytable.textile