Skip to content

Instantly share code, notes, and snippets.

@naosim
Created June 5, 2018 21:30
Show Gist options
  • Save naosim/088e19050fe717dd53498a7a2b2c43a3 to your computer and use it in GitHub Desktop.
Save naosim/088e19050fe717dd53498a7a2b2c43a3 to your computer and use it in GitHub Desktop.
htmlのテーブルからmarkdownを作る
<!DOCTYPE html>
<div id="div20180606">
<table border="1">
<tr><th>名前</th><th>備考</th>
<tr><td>ほげ</td><td>改行<br>テスト</td></tr>
<tr><td>ふー</td><td>改行<br>テスト</td></tr>
</table>
</div>
<script>
function table2md(tableDom) {
// htmlからdomを作る
var dom = new DOMParser().parseFromString(tableDom.outerHTML, 'text/html') // text/xmlだとinnerTextが使えない
var nodeList2Ary = (nodeList) => {
nodeList.map = Array.prototype.map
nodeList.filter = Array.prototype.filter
nodeList.reduce = Array.prototype.reduce
return nodeList
}
// HTタグまたはTRタグを取得する
var thOrTdList = (trDom, cb) => {
var l = trDom.querySelectorAll('td')
if(!l || l.length == 0) {
l = trDom.querySelectorAll('th')
}
return nodeList2Ary(l)
}
// markdownのテーブルのセパレータ作成
var createSeparetorLine = (length) => {
var ary = []
for(var i = 0; i < length; i++) {
ary.push('---')
}
return ary.join('|')
}
// cellをBRタグだけ残してテキストにする
var cell2Text = (cell) => cell.innerText.split('\n').join('<br>').trim()
return nodeList2Ary(dom.querySelectorAll('tr')).reduce((lines, tr, i) => {
var ary = thOrTdList(tr).map(cell2Text)
lines.push(ary.join(' | '))
if(i == 0) {// ヘッダ行の次にセパレータを入れる
lines.push(createSeparetorLine(ary.length))
}
return lines
}, []).join('\n')
}
var result = table2md(document.querySelector('#div20180606>table'))
console.log(result)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment