Created
August 13, 2025 13:08
-
-
Save elsewhat/c449808dcc761a516a61ee03b52688c8 to your computer and use it in GitHub Desktop.
Convert to html table to markdown table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function tableToMarkdown(tableEl) { | |
if (!tableEl || tableEl.tagName !== 'TABLE') { | |
throw new Error('Pass a <table> element'); | |
} | |
const escapeCell = (t) => | |
String(t ?? '') | |
.replace(/\|/g, '\\|') // escape pipes | |
.replace(/\r?\n+/g, ' ') // collapse newlines | |
.trim(); | |
// 1) Find header cells | |
let headerCells = []; | |
const thead = tableEl.querySelector('thead'); | |
if (thead) { | |
const headRow = thead.querySelector('tr'); | |
if (headRow) headerCells = Array.from(headRow.querySelectorAll('th,td')); | |
} | |
// Fallback: first row in the table (before using tbody rows) | |
if (headerCells.length === 0) { | |
const firstRow = tableEl.querySelector('tr'); | |
if (firstRow) headerCells = Array.from(firstRow.querySelectorAll('th,td')); | |
} | |
const headers = headerCells.map((c) => escapeCell(c.textContent)); | |
const colCount = headers.length || Math.max( | |
0, | |
...Array.from(tableEl.querySelectorAll('tr')).map( | |
(tr) => tr.querySelectorAll('th,td').length | |
) | |
); | |
// If still no headers, synthesize generic ones | |
const finalHeaders = headers.length | |
? headers | |
: Array.from({ length: colCount }, (_, i) => `Col ${i + 1}`); | |
// 2) Collect body rows (skip the header row if we used it) | |
const allRows = Array.from(tableEl.querySelectorAll('tr')); | |
const headerRowEl = headerCells.length ? headerCells[0].closest('tr') : null; | |
const bodyRows = allRows.filter((tr) => tr !== headerRowEl); | |
const rows = bodyRows.map((tr) => { | |
const cells = Array.from(tr.querySelectorAll('th,td')).map((c) => | |
escapeCell(c.textContent) | |
); | |
// Normalize width to colCount | |
if (cells.length < colCount) { | |
while (cells.length < colCount) cells.push(''); | |
} else if (cells.length > colCount) { | |
cells.length = colCount; | |
} | |
return cells; | |
}); | |
// 3) Build Markdown | |
let out = ''; | |
out += `| ${finalHeaders.join(' | ')} |\n`; | |
out += `| ${finalHeaders.map(() => '---').join(' | ')} |\n`; | |
for (const r of rows) { | |
out += `| ${r.join(' | ')} |\n`; | |
} | |
return out; | |
} | |
// Usage: | |
var el = document.querySelector('#table1'); | |
var md = tableToMarkdown(el); | |
console.log(md); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment