r/tinycode • u/woqr • 2d ago
world's smallest syntax highlighter? (80 chars)
This only bolds keywords: s.replace(/[a-z]+/g,x=>{try{eval("let "+x)}catch{x=`<b>${x}</b>`}return x})
For a prettier, more robust version, see: https://github.com/bacionejs/editor
Also, if you don't like the built-in GitHub code view, try this: https://github.com/bacionejs/bacionejs/blob/main/viewsource.html You can see the behavior of viewsource.html by clicking on the 3x5 cards in any of my repos.
10
Upvotes
3
u/nexe mod 2d ago
Super nice! Also actually like the sample game
3
u/jakiestfu 2d ago
Run every character through eval and attempt to define it as a variable? This is all ridiculous
1
u/YellowBunnyReddit 1d ago edited 1d ago
The regex only looking for lowercase letters is wrong, as a keyword appearing as a substring of an identifier, surrounded by non-lowercase letters, would still be highlighted. Here is the shortest regex I could find that is correct in this aspect:
/[a-z_$][\w$]*/giOf course there are more problems like key words contained in string literals or (potentially nested) template literals which at least requires a context free parser.
Also, this only catches the strictly reserved keywords and not all reserved words, which may or may not be what you want.