qwik-cms/libs/codeHighlighter.js
2021-08-07 10:46:48 +02:00

16 lines
623 B
JavaScript

import hljs from 'highlight.js'
export function highlight(code, lang) {
// Check if hljs recognises the language, else assume 'plaintext'.
const language = hljs.getLanguage(lang) ? lang : 'plaintext'
// Highlight it with the corresponding language.
return hljs.highlight(
// Switch out bullet points (•) to spaces (for proper indentation).
code.replace(/•/g, " "), { language })
// Replace newlines with <br> tags.
.value.replace(/\n/g, "<br>")
// Replace spaces with '&nbsp;' to forcefully render them.
.replace(/ /g, "&nbsp;"
)
}