MoreLesson 276Free preview
Syntax Highlighter
This lesson is part of How To · All levels
Summary
Syntax highlighters give the code a color to make the structure and tokens easy to read. For simple pages, the code is displayed inside <pre><code> and the special character is escaped first. You can use a library like Prism or a simple highlight with regex for small needs. (highlight.js)
Key points
- Escape &, <, and > before displaying the code so it is not considered HTML.
- <pre> retains spaces and new lines; <code> marks that it contains code.
- Library highlighters are more reliable because they understand the grammar of programming languages.
- Never enter unsanitized user code through innerHTML.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.