rehype plugin to add id attributes to headings
npm install @microflash/rehype-slugifyids to headings using a slugger of your choice
ids to headings. It looks for headings ( through ) that do not yet have ids and adds id attributes to them based on the text they contain. You'll have to provide an implementation of the algorithm that does that, such as github-slugger, @sindresorhus/slugify,etc.
rehype-autolink-headings, adds links to these headings back to themselves, which is useful as it lets users more easily link to particular sections.
rehype-slug does not allow (e.g, additional language support, custom replacements, etc)
sh
npm install @microflash/rehype-slugify
`
In Deno, with esm.sh:
`js
import rehypeSlugify from 'https://esm.sh/@microflash/rehype-slugify'
`
In browsers, with esm.sh:
`html
`
Use
Say we have the following file example.html:
`html
Lorem ipsum
Dolor sit amet 😪
consectetur & adipisicing
elit
elit
`
And our module example.js looks as follows:
`js
import Slugger from 'github-slugger'
import { read } from 'to-vfile'
import { rehype } from 'rehype'
import rehypeSlugify from '@microflash/rehype-slugify'
const slugger = new Slugger()
main()
async function main() {
const file = await rehype()
.data('settings', { fragment: true })
.use(rehypeSlugify, {
reset() {
slugger.reset()
},
slugify(text) {
return slugger.slug(text)
}
})
.process(await read('example.html'))
console.log(String(file))
}
`
Running that with node example.js yields:
`html
Lorem ipsum
Dolor sit amet 😪
consectetur & adipisicing
elit
elit
`
API
The default export is rehypeSlugify.
$3
The following options are available. All of them are required.
- reset: function that resets the slug counter
- slugify: function that slugifies the text
Security
Use of @microflash/rehype-slugify can open you up to a cross-site scripting (XSS) attack as it sets id attributes on headings, which causes what is known as "DOM clobbering". Please use rehype-sanitize and see its Example: headings (DOM clobbering) for information on how to properly solve it.
Related
- rehype-slug — opinionated plugin to generate slugs using github-slugger
- rehype-autolink-headings` — add links to headings with IDs back to themselves