Skip to content

Commit

Permalink
feat(project): add markdown component
Browse files Browse the repository at this point in the history
  • Loading branch information
royschut committed Jun 8, 2021
1 parent b6c0a42 commit a9308de
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/components/MarkDown/MarkDown.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React from 'react';

const MARKDOWN_LINK_REGEX = /\[([^[]+)]\(((https?:\/\/|www\.)?[^)]+)\)/gi;
const MARKDOWN_ITALIC_REGEX = /(?:\*|_)(\S[\s\S]*?)(?:\*|_)/gi;
const MARKDOWN_STRONG_REGEX = /(?:\*{2}|_{2})(\S[\s\S]*?)(?:\*{2}|_{2})/gi;
const MARKDOWN_ITALIC_STRONG_REGEX = /(?:\*{3}|_{3})(\S[\s\S]*?)(?:\*{3}|_{3})/gi;
const MARKDOWN_HEADERS_REGEX = /^(#{1,6})(.*)$/gm;
const LINEBREAK_REGEX = /(?:\r\n|\r|\n)/g;

type Props = {
markDownString: string;
};

const parseMarkdown = (value: string): string =>
value
.replace(/<[^>]+>/gm, '') // remove html should run first
.replace(MARKDOWN_HEADERS_REGEX, (...[, header, title]) => {
return '<h' + header.length + '>' + title.trim() + '</h' + header.length + '>';
})
.replace(MARKDOWN_ITALIC_STRONG_REGEX, (...[, word]) => `<strong><em>${word}</em></strong>`)
.replace(MARKDOWN_STRONG_REGEX, (...[, word]) => `<strong>${word}</strong>`)
.replace(MARKDOWN_ITALIC_REGEX, (...[, word]) => `<em>${word}</em>`)
.replace(MARKDOWN_LINK_REGEX, (...[, word, link]) => {
const target = /^(https?|www\.|\/\/)/.test(link) ? ' target="_blank"' : '';

return `<a href="${link}"${target}>${word}</a>`;
})
.replace(LINEBREAK_REGEX, '<br />'); // linebreak formatter should run last

const MarkDown: React.FC<Props> = ({ markDownString }: Props) => {
return <div dangerouslySetInnerHTML={{ __html: parseMarkdown(markDownString) }} />;
};

export default MarkDown;

0 comments on commit a9308de

Please sign in to comment.