qwik-site/libs/codeHighlighter.js

16 lines
623 B
JavaScript
Raw Normal View History

2021-08-09 17:44:53 +02:00
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;"
)
}