Skip to content

Instantly share code, notes, and snippets.

@SpiffGreen
Created July 28, 2021 02:18
Show Gist options
  • Save SpiffGreen/34bf32ced0380bf57359bcdf654855da to your computer and use it in GitHub Desktop.
Save SpiffGreen/34bf32ced0380bf57359bcdf654855da to your computer and use it in GitHub Desktop.
A simple function that evaluates and produces html from markdown
/**
* @description A simple function to parse markdown code into HTML
*/
const parseMarkdown = (str) => str.replace(/^# (.*$)/gim, "<h1>$1</h1>")
.replace(/^## (.*$)/gim, "<h2>$1</h2>")
.replace(/^### (.*$)/gim, "<h3>$i</h3>")
.replace(/^#### (.*$)/gim, "<h4>$i</h4>")
.replace(/^##### (.*$)/gim, "<h5>$i</h5>")
.replace(/^###### (.*$)/gim, "<h6>$i</h6>")
.replace(/^\> (.*$)/gim, "<blockquote>$1</blockqoute>")
.replace(/\*\*(.*)\*\*/gim, '<b>$1</b>')
.replace(/__(.*)__/g, "<b>$1</b>")
.replace(/\*(.*)\*/gim, '<i>$1</i>')
.replace(/_(.*)_/g, "<i>$1</i>")
.replace(/!\[(.*?)\]\((.*?)\)/gim, "<img alt='$1' src='$2' />")
.replace(/\[(.*?)\]\((.*?)\)/gim, "<a href='$2'>$1</a>")
.replace(/\`\`\`([.\s\S\d]*)\`\`\`/g, "<code>$1</code>")
.replace(/<\s*script\s*[^>]*>[.\s\S\d]*<\s*\/\s*script[^>]*>/g, "")
.replace(/\n$/gim, '<br />').trim();
const testStr = `
# Hello World
**This is a bold text**
__Spiff__
*Italic Text*
_Italic Text2_
[MIT](./LICENSE.md)
![A face](./pic1.jpg)
> Hello World
\`\`\`
This is a piece of code
\`\`\`
<><script src="evil.com" > < / script >`;
const testStr2 = `
## FlattenArray
Flatten an array of arrays into one or more. It flexible enough that you can dictate the maximum depth it unveils.
### Example
\`\`\`js
const arr = [
[1, 2, 3],
[4, 5, 6],
7, 8, 9,
[10,
[11,
[12,
[13, 14, 15]
],
16,
],
17,
],
18
];
console.log(flattenArr(arr, 3));
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, [ 13, 14, 15 ], 16, 17, 18 ]
console.log(flattenArr(arr));
/* [
1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18
] */
\`\`\`
### Author
Spiff Jekey-Green
### License
[MIT](./LICENSE) License
`;
console.log(parseMarkdown(testStr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment