JSFiddle - React, Tailwind, and code Playground
by Eugene Trounev
HTML
<div id="content">
</div>
SCSS
table {
th,td {
border: 1px solid #eee;
padding: 5px 10px;
}
}
JavaScript
const content = `First Header|Second Header|Third Header|
|--- | --- | --- |
Content|*Long Cell*||
Content|**Cell**|Cell|
**New** section|More|\`Data\`|
And more|||`;
const isHeaderSplitCell = (cell) => cell.indexOf("---") > -1;
const MarksRegex = [
[/\*\*(.*)\*\*/gim, "<b>", "</b>"],
[/\*(.*)\*/gim, "<i>", "</i>"],
[/`(.*)`/gim, "<code>", "</code>"]
]
const ColspanRegex = /(?<!^)(\|{1,})/gm;
const RowSanitizeRegex = /^\||\|$/gm;
const formatMarks = (content) => {
return MarksRegex.reduce((acc, mark) => acc.replace(mark[0], `${mark[1]}$1${mark[2]}`), content);
/* return content
.replace(/\*\*(.*)\*\gim, '<b>$1</b>') // bold text
.replace(/\*(.*)\gim, '<i>$1</i>') // italic text
.replace(/`(.*)`/gim, '<code>$1</code>'); // code text */
}
const ApplyRegex = (regex, str) => {
let m, arr = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
arr[groupIndex] = match;
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
return arr;
}
const renderRow = (isHeader = false) => (row) => {
const _row = row.replace(RowSanitizeRegex, "");
const tag = isHeader ? "th" : "td";
let html = "<tr>";
const colspan = ApplyRegex(ColspanRegex,row);
console.log(colspan);
debugger;
const cols = _row.split("|");
html += cols.map((col, i) => {
if (col === "") return null;
let html = `<${tag} colspan="${colspan[i]}">`;
html += formatMarks(col);
html += `</${tag}>`;
return html;
}).filter(c => c !== null).join("");
html += "</tr>";
return html;
}
function renderMD(content) {
let html = "<table>";
const rows = content.split("\n");
const headerIndex = rows.findIndex(r => isHeaderSplitCell(r.split("|")[0]));
const headerRows = rows.slice(0, headerIndex);
const bodyRows =...