Home > OS >  Regex to convert markdown to html
Regex to convert markdown to html

Time:10-04

My goal is to take a markdown text and create the necessary bold/italic/underline html tags. Looked around for answers, got some inspiration but I'm still stuck.

I have the following typescript code, the regex matches the expression including the double asterisk:

var text = 'My **bold\n\n** text.\n'
var bold = /(?=\*\*)((.|\n)*)(?<=\*\*)/gm
var html = text.replace(bold, '<strong>$1</strong>');   
console.log(html)

Now the result of this is : My <\strong>** bold\n\n **<\strong> text. Everything is great aside from the leftover double asterisk. I also tried to remove them in a later 'replace' statement, but this creates further issues.

How can I ensure they are removed properly?

CodePudding user response:

Just make another call to replaceAll removing the ** with and empty string.

var text = 'My **bold\n\n** text.\n'
var bold = /(?=\*\*)((.|\n)*)(?<=\*\*)/gm
var html = text.replace(bold, '<strong>$1</strong>');
html = html.replaceAll(/\*\*/gm,'');
console.log(html)

CodePudding user response:

Based on Koen Vendrik's CodePen Home JavaScript Markdown Parser, you can use the following regular expression: /[\*\_]{2}([^\*\_] )[\*\_]{2}/g

var text = 'My **bold\n\n** text.\n'
var bold = /[\*\_]{2}([^\*\_] )[\*\_]{2}/g
var html = text.replace(bold, '<strong>$1</strong>');   
console.log(html)

  • Related