Syntax highlighting using Angulars pipes and regular expressions
Besides story-telling code writing syntax highlighting is an important thing in order to let other people read your code easily. Since there are many different programming languages with each its own syntax, there are quite some rules to have in mind in order to colorize the code successfully.
This article starts building a basic Angular pipe you can use like in the following snippet and fills it slowly with additional content.Angular pipes a great way to modify or transform text in a similar way for each input. So if we are going to display some code, we'd like to transform our code so that it is colorized everytime in the same way.
The folder structure of the pipe and its config looks like follows
syntax.pipe.tsLet's start with the pipe:This pipe filters the first line and wants to find a string similar to syntax:typescript or whatever the syntax is. If it has found a phrase like this it matches the word behind the colon with the defined languages in ./syntax-rules. The folders index file exports an Array of our defined language configurationsSyntaxConfig is just a TypeScript interface.
Defining language rules
The language file follow the SyntaxConfig interface. Within there you can define the language as a string ID (lang). The specify the keywords, afterwards set the colors for strings, comments and decorators.