Server-side syntax highlighting with one regex and zero client JavaScript

Abstract

Build a small code highlighter in TypeScript: one regex with named groups, HTML escaping, and CSS variables for light and dark themes. Tested, with real output.

Code blocks on the web usually arrive with a JavaScript highlighter attached. This site does it differently: the highlighting happens on the server, the page ships only HTML and CSS, and no script runs in the browser. This tutorial builds a small version of the same idea in TypeScript.

The code below was type-checked with TypeScript 7.0.2 in strict mode and run on Node 24. The approach mirrors the highlighter used by this site, which is a longer version with grammars for Rust, TypeScript, Bash and JSON.

The idea

A highlighter does two jobs: split code into tokens (comments, strings, numbers, keywords) and wrap each token in an element with a class. CSS then colours the classes. If the splitting runs on the server, the browser needs nothing but the stylesheet.

Step 1: escape everything

Code contains <, > and &. If you put it into HTML unescaped, a snippet like <script> becomes markup. Escape every character of input, always:

const MAP: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
const esc = (s: string): string => s.replace(/[&<>"']/g, (ch) => MAP[ch]!);

Step 2: one regex, named groups

const KEYWORDS = new Set(['const', 'let', 'function', 'return', 'if', 'else', 'type', 'true', 'false', 'null']);

// One regex, named groups, tried left to right at each position.
const TOKEN = new RegExp(
  [
    String.raw`(?<c>//[^\n]*|/\*[\s\S]*?\*/)`,
    String.raw`(?<s>"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\\n])*')`,
    String.raw`(?<n>\b\d[\d_]*(?:\.\d+)?\b)`,
    String.raw`(?<w>[A-Za-z_$][\w$]*)`,
  ].join('|'),
  'g',
);

The four groups are comments (c), strings (s), numbers (n) and words (w). Joined with |, they form one pattern. Regex alternation works from the earliest position in the text: the engine finds the leftmost place where any alternative matches and uses that match. This is what makes the next case come out right. In "a // not a comment" the string starts first, so the whole string is consumed as one token and the // inside it is never considered a comment.

String.raw keeps backslashes as written, so the regex source needs no double escaping.

Step 3: walk the matches

const span = (cls: string, text: string) => `<span class="tk-${cls}">${esc(text)}</span>`;

export function highlight(code: string): string {
  let out = '';
  let last = 0;
  for (const m of code.matchAll(TOKEN)) {
    const at = m.index ?? 0;
    out += esc(code.slice(last, at));
    const g = m.groups ?? {};
    if (g.c) out += span('c', m[0]);
    else if (g.s) out += span('s', m[0]);
    else if (g.n) out += span('n', m[0]);
    else if (g.w && KEYWORDS.has(g.w)) out += span('k', m[0]);
    else out += esc(m[0]);
    last = at + m[0].length;
  }
  return out + esc(code.slice(last));
}

Text between matches is escaped and copied through. Each token is escaped inside its span. Words that are not keywords are plain text. The final line copies whatever follows the last match.

What it produces

For these inputs:

highlight('const n = 42; // answer');
highlight('const s = "a // not a comment";');
highlight('if (a < b && c > d) return "<script>alert(1)</script>";');

the output was:

<span class="tk-k">const</span> n = <span class="tk-n">42</span>; <span class="tk-c">// answer</span>
<span class="tk-k">const</span> s = <span class="tk-s">&quot;a // not a comment&quot;</span>;
<span class="tk-k">if</span> (a &lt; b &amp;&amp; c &gt; d) <span class="tk-k">return</span> <span class="tk-s">&quot;&lt;script&gt;alert(1)&lt;/script&gt;&quot;</span>;

On the second line the string stays one token, so the // inside it is not mistaken for a comment. The third input is deliberately hostile: every angle bracket is escaped, so the script text stays inert and no markup from the input survives. The comparison operators in a < b && c > d are escaped too.

Step 4: colour it with CSS

The classes need rules. Using CSS custom properties lets one stylesheet serve light and dark mode. These are the values this site uses for keywords, strings, comments and numbers:

:root { --tk-k:#cf222e; --tk-s:#0a3069; --tk-c:#6e7781; --tk-n:#0550ae; }
@media (prefers-color-scheme: dark) {
  :root { --tk-k:#ff7b72; --tk-s:#a5d6ff; --tk-c:#8b949e; --tk-n:#79c0ff; }
}
.tk-k { color: var(--tk-k); }
.tk-s { color: var(--tk-s); }
.tk-c { color: var(--tk-c); font-style: italic; }
.tk-n { color: var(--tk-n); }

The browser applies the right palette from the user’s colour-scheme preference. No script is involved.

Limits and safeguards

  • Input size. Regex work grows with input, so the real highlighter returns the code escaped but uncoloured above 20,000 characters.
  • Unknown languages. If no grammar matches the language name, return the escaped text unchanged.
  • Simplifications. This version ignores template literals, regex literals and types. A fuller grammar adds those per language.
  • Not a parser. A regex tokenizer will sometimes colour oddly. For a blog, it only has to be right on the code you publish.

Conclusion

One regex, one loop and one escape function give you highlighted code without shipping a single byte of JavaScript.[1] The same approach keeps a strict content security policy simple, because there is no script to allow.


  1. Reviewer 2 would like to know whether the highlighter highlights itself. The authors say it does, with the confidence of a regular expression. ↩︎