How to add different colors for each word (code examples)

Hi Friends!

As I was reading an introduction about react hooks I ask myself a totally different question when I saw the code examples… :sweat_smile:

How to add so much different colors for each word in the easiest way? I guess a <span> tag is not the way to go here, but how to archive these different colors?

Is it a Javascript logic which tells which words are red, blue, gray etc. or is it an external library which will be formatting the code examples like in an IDE?

Here a screenscot:

Thanks for answers!

Hello there,

Some languages/IDEs/interpreters might do this differently, but, at the end of the day, the text you write is interpreted into something like an AST. The AST contains information such as what kind of text the text is (e.g. a keyword, string, number, etc.), and the language analyser has a map of colours for each type.

For a text editor like VSCode - built using Electron - yes, it is JavaScript logic mixed with a bunch of spans and some CSS which handles the frontend of displaying those colours.

For more of an idea, you can:

  1. Open the freeCodeCamp editor (which uses VSCode’s Monaco editor), and inspect the page:

  2. Take a look at how a language like JavaScript is interpreted:

Hope this helps

1 Like

Awesome, thank you!! :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.