Adam Khoury

Donate funds to show love and support

Click the button below to donate funds securely online. You can use your PayPal account or a credit card.

Your donations help free up my time to produce more content and assist in covering server costs. It's also a great way to say thanks for the content!

Application Configuration

Adam will be adding options here soon.

How to Program Code Syntax Highlighter Using JavaScript

Published :
Author :
Adam Khoury

Learn to begin programming a custom code syntax highlighter for displaying code in a document with colored highlights and other styling features.

Here are several reasons why a developer may want to program their own code syntax highlighter from scratch:

1. You may not like how much existing syntax highlighters slow down your documents. 2. You may want to gain reputation by offering your finished program to others online. 3. You may just want a few key features instead of a very bulky program like most syntax highlighters are. 4. You may get a certain satisfaction from programming it yourself. 5. You may have this as a programming assignment in your school. 6. You may want to learn more and get better at Regular Expression programming for web projects. Completing a syntax highlighter program will assure that you gain experience and knowledge dealing with regular expression logic. example.html <!doctype html> <html> <head> <meta charset="UTF-8"> <style> code { display: block; white-space: pre-wrap; border: 1px solid #000; padding: 10px; line-height: 1.5em; font-family: "Lucida Console", Monaco, monospace; } .code-str { color:#090; } .code-elem{ color: #F90; } .code-comment { color:#999; } </style> <script> function syntaxHighlights() { var ca = document.getElementsByTagName("code"); for(var i=0; i < ca.length; i++){ var data = ca[i].innerHTML; data = data.replace(/"(.*?)"/g, '<span class="code-str">&quot;$1&quot;</span>'); data = data.replace(/&lt;(.*?)&gt;/g, '<span class="code-elem">&lt;$1&gt;</span>'); data = data.replace(//* (.*?) *//g, '<span class="code-comment">/* $1 */</span>'); ca[i].innerHTML = data; } } window.addEventListener("load", syntaxHighlights); </script> </head> <body> <h2>Code example:</h2> <code>&lt;script&gt; /* Create a string object variable */ var name = "Adam"; &lt;/script&gt; &lt;h2 id="h21"&gt;Welcome Visitor&lt;/h2&gt; &lt;p&gt;When in Rome, do as the Romans do.&lt;/p&gt;</code> </body> </html>