How TO – Create a Syntax Highlighter
原理其實很簡單
首先解析程式碼
再套上 <span> 標籤
而 <span> 標籤有定義好的顏色樣式
所有通常有一支 JavaScript 負責解析
一支 CSS 負責樣式
範例:
原本的 code 是
<html>
<body>
<h1>Hello world!</h1>
</body>
</html>
背後的 html 長這樣
<html><br>
<body><br>
<h1>Hello world!</h1><br>
</body><br>
</html>
加工後會變成這樣

畫面上就是

因此這牽涉到大量的字串處理
而且不同語言的解析方式當然不一樣
甚至要兼容同語言中的不同寫法
本來想自己刻,後來果斷放棄