javascriptjqueryhtmlcssshowdown

How to print table text to md table using showdown.js?


I'd like to print md table by using showdown.js. But, it doesn't seem to convert to markdown table correctly as I expected.

I tried setting options('table option') to be changed 'true' and converting text to md. but, doesn't work.

Below is the functions I implemented, for your information.

setMdConvert() <= As I said, I just tried all options for true.

getTechDescriptionMd() <= A test function for converting arbitary markdown text to markdown table

function setMdConvert() {
    var mdConverter = new showdown.Converter();
    var options = showdown.getOptions();
    var keys = Object.keys(options);

    keys.forEach((key) => {
        if(options[key].constructor === boolConstructor)
            mdConverter.setOption(key, true);
    });

    console.log(mdConverter.getOptions());

    return mdConverter;
}

function getTechDescriptionMd() {
    var text = '| h1    |    h2   |      h3 |' +
               '|:------|:-------:|--------:|' +
               '| 100   | [a][1]  | ![b][2] |' +
               '| *foo* | **bar** | ~~baz~~ |';
    var html = mdConverter.makeHtml(text);

    $('.desc-viewer').html(html);
}

result:

| h1 | h2 | h3 ||:------|:-------:|--------:|| 100 | [a][1] | ![b][2] || foo | bar | baz |

Is there any other option that I miss?


Solution

  • Here's a modified version of .getTechDescriptionMd() that works for me. I added the linebreaks that I already mentioned in my comment from yesterday, plus I initialized mdConverter and set its option 'tables' to true (inspired by the documentation).

    It looks like this now:

    function getTechDescriptionMd() {
        var text = '| h1    |    h2   |      h3 |\n' +
                   '|:------|:-------:|--------:|\n' +
                   '| 100   | [a][1]  | ![b][2] |\n' +
                   '| *foo* | **bar** | ~~baz~~ |';
    
        var mdConverter = new showdown.Converter();
        mdConverter.setOption('tables', true);
        var html = mdConverter.makeHtml(text);
        $('.desc-viewer').html(html);
    }
    

    The result I'm getting is:

    <table>
    <thead>
    <tr>
    <th style="text-align:left;">h1</th>
    <th style="text-align:center;">h2</th>
    <th style="text-align:right;">h3</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td style="text-align:left;">100</td>
    <td style="text-align:center;">[a][1]</td>
    <td style="text-align:right;">![b][2]</td>
    </tr>
    <tr>
    <td style="text-align:left;"><em>foo</em></td>
    <td style="text-align:center;"><strong>bar</strong></td>
    <td style="text-align:right;">~~baz~~</td>
    </tr>
    </tbody>
    </table>