Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict only certain formatting only with showdown.js Markdown expression library

I am using showdown.js that can be downloaded from https://github.com/showdownjs/showdown/

and the question is I am trying to allow only certain formatting? E.g. only bold formattings are allowed, the rest is not converted and is formatting discarded for example

If I am writing the text which is a Markdown Expression below

"Text attributes _italic_, *italic*, __bold__, **bold**, `monospace`."

the output of the above would be below

<p>Text attributes <em>italic</em>, <em>italic</em>, <strong>bold</strong>, <strong>bold</strong>, <code>monospace</code>.

after conversion. Now what I want is when converting, it should convert the bold expression only rest of the expressions it should discard.

I am using the below code to convert the markdown expression into a normal text below

var converter = new showdown.Converter(),
//Converting the response received in to html format 
html = converter.makeHtml("Text attributes _italic_, *italic*, __bold__, **bold**, `monospace`.");

Thank you!

like image 513
Pradeep Gaba Avatar asked Jun 08 '16 06:06

Pradeep Gaba


1 Answers

Out-of-the-box this is not possible with showdown.js. This would require creating a custom build of showdown.js from source, removing the subParsers that you do not want.

There are other mechanisms in place that could be used to have showdown only convert bold markdown, like listening to dispatched events pre and post parsing, but since you only want bold converted this is not an approach i would take, as it would require writing a lot of code for something that could take only a few lines of code.

What you could do instead is use the part of showndown.js that parses/converts the bold parts, like so:

function markdown_bold(text) {
    html = text;
    //underscores
    html = html.replace(/(^|\s|>|\b)__(?=\S)([^]+?)__(?=\b|<|\s|$)/gm, '$1<strong>$2</strong>');
    //asterisks
    html = html.replace(/(\*\*)(?=\S)([^\r]*?\S[*]*)\1/g, '<strong>$2</strong>');
    return html;
}

Source.

like image 159
Elwin Arens Avatar answered Oct 14 '22 07:10

Elwin Arens