Skip to content

Instantly share code, notes, and snippets.

@yinyanfr
Created January 12, 2020 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yinyanfr/08dea90f1cbb79faf8a3dbcbbb236820 to your computer and use it in GitHub Desktop.
Save yinyanfr/08dea90f1cbb79faf8a3dbcbbb236820 to your computer and use it in GitHub Desktop.
Building a menu for markdown html by adding an id to each h tag and collecting all the titles
// some safe html text parsed from a markdown file
// e.g. your awesome novel
let html = `
<h1>hhh1</h1>
<h2 class="title">hhh2<p>ppp</p></h2>
<h3>hhh3</h3>
<h4>hhh4</h4>
<h5>hhh5</h5>
`
// the THING
const regex = /<(h[1-5])((?! *id)[^>]*)>(.*)<\/\1>/
const titlelist = []
while(html.match(regex)){
const id = uuid()
html = html.replace(regex, `<$1 id="${id}"$2>$3</$1>`)
titlelist.push({
tag: RegExp.$1,
id,
title: RegExp.$3
})
}
console.log(html)
console.log(titlelist)
// output
// html
/*
<h1 id="c078ca11-bd33-41c4-9907-82f3f3fa8241">hhh1</h1>
<h2 id="bfa5770b-2dd8-4eae-8e60-d0fceb2df87d" class="title">hhh2<p>ppp</p></h2>
<h3 id="d042a08f-7937-41ef-9166-890de6988281">hhh3</h3>
<h4 id="82440b83-3042-4086-8562-2a312d207488">hhh4</h4>
<h5 id="9bafd962-6292-4cf5-80a0-58789fd0673b">hhh5</h5>
*/
// titlelist
/*
[
{
tag: 'h1',
id: 'c078ca11-bd33-41c4-9907-82f3f3fa8241',
title: 'hhh1'
},
{
tag: 'h2',
id: 'bfa5770b-2dd8-4eae-8e60-d0fceb2df87d',
title: 'hhh2<p>ppp</p>'
},
{
tag: 'h3',
id: 'd042a08f-7937-41ef-9166-890de6988281',
title: 'hhh3'
},
{
tag: 'h4',
id: '82440b83-3042-4086-8562-2a312d207488',
title: 'hhh4'
},
{
tag: 'h5',
id: '9bafd962-6292-4cf5-80a0-58789fd0673b',
title: 'hhh5'
}
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment