Syntax highlighting code with Javascript

javascript

To syntax highlight code with JavaScript, you can use a syntax highlighting library that parses the code and applies formatting to the appropriate parts of the code based on the language syntax.

There are many syntax highlighting libraries available for JavaScript, such as Prism, Highlight.js, and CodeMirror. These libraries allow you to specify the language of the code and the theme to use for the syntax highlighting, and they will automatically apply the appropriate formatting to the code.

Here is an example of how you can use the Prism library to syntax highlight a code block:

<!-- include the Prism CSS and JavaScript files in your HTML -->
<link rel="stylesheet" href="/path/to/prism.css" />
<script src="/path/to/prism.js"></script>

<!-- create a code block with the class "language-javascript" and the desired theme -->
<pre><code class="language-javascript" data-theme="tomorrow">
function greet(name) {
  console.log('Hello, ' + name + '!');
}
greet('World');
</code></pre>

This will apply syntax highlighting to the code block using the JavaScript language and the “Tomorrow” theme.

You can also use the Prism.highlightAll() function to automatically syntax highlight all code blocks on the page:

<!-- include the Prism CSS and JavaScript files in your HTML -->
<link rel="stylesheet" href="/path/to/prism.css" />
<script src="/path/to/prism.js"></script>

<!-- create a code block with the class "language-javascript" and the desired theme -->
<pre><code class="language-javascript" data-theme="tomorrow">
function greet(name) {
  console.log('Hello, ' + name + '!');
}
greet('World');
</code></pre>

<!-- syntax highlight all code blocks on the page -->
<script>
  Prism.highlightAll();
</script>

This will apply syntax highlighting to all code blocks on the page that have a language class specified (e.g. language-javascript).

Keep in mind that you will need to include the Prism CSS and JavaScript files in your HTML in order to use the library. You can also customize the appearance of the syntax highlighting by modifying the CSS styles or by using a different theme.