How to Program Code Syntax Highlighter Using JavaScript
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">"$1"</span>');
data = data.replace(/<(.*?)>/g, '<span class="code-elem"><$1></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><script>
/* Create a string object variable */
var name = "Adam";
</script>
<h2 id="h21">Welcome Visitor</h2>
<p>When in Rome, do as the Romans do.</p></code>
</body>
</html>