How to Create and Use a Syntax Highlighter using JavaScript?
Last Updated :
20 Aug, 2024
A syntax highlighter is a tool that colorizes the source code of programming languages, making it easier to read by highlighting keywords, operators, comments, and other syntax elements in different colors and fonts. In JavaScript, you can create a syntax highlighter by either manually writing your own code or by using existing libraries.
These are the following approaches to create and use a Syntax Highlighter using JavaScript:
Using Regular Expressions
This approach involves using regular expressions to match and replace various parts of the code with HTML elements that have specific CSS classes applied. Each regex pattern corresponds to a specific type of syntax (e.g., keywords, comments, strings).
Example: In this example, JavaScript code is parsed with regular expressions, and different parts of the code (comments, keywords, strings) are wrapped with <span> elements with appropriate classes.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Regular Expression-Based Syntax Highlighter</title>
<style>
.keyword {
color: blue;
font-weight: bold;
}
.operator {
color: red;
}
</style>
</head>
<body>
<pre id="code">
let x = 5 + 10;
if (x > 10) {
console.log("x is greater than 10");
}
</pre>
<script>
document.addEventListener('DOMContentLoaded', function () {
let codeElement = document.getElementById('code');
let code = codeElement.textContent;
// Escape special HTML characters
code = code.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
// Combine regexes to capture keywords and operators
let combinedRegex = /(\b(let|if|else|console|log)\b)|([\+\-\*\/=])/g;
// Replace with spans for keywords and operators
code = code.replace(combinedRegex, function
(match, keyword, keywordGroup, operator) {
if (keyword) {
return `<span class="keyword">${keyword}</span>`;
} else if (operator) {
return `<span class="operator">${operator}</span>`;
}
return match;
});
codeElement.innerHTML = code;
});
</script>
</body>
</html>
Output:
OutputUsing Tokenization and Parsing
In this approach, the code is first tokenized into its components (keywords, operators, identifiers, etc.), and each token is analyzed and styled according to its type. This is more complex but offers finer control and better accuracy.
Example: This splits code into tokens, analyzes each token, and applies specific styles based on token types (e.g., keywords, operators) to enhance code readability.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Tokenization-Based Syntax Highlighter</title>
<style>
.keyword {
color: blue;
font-weight: bold;
}
.operator {
color: red;
}
</style>
</head>
<body>
<pre id="code">
let x = 5 + 10;
if (x > 10) {
console.log("x is greater than 10");
}
</pre>
<script>
document.addEventListener('DOMContentLoaded', function () {
let codeElement = document.getElementById('code');
let code = codeElement.textContent;
// Split the code into tokens
let tokens = code.split(/(\s+|\b)/);
// Highlight keywords
let keywords = ['let', 'if', 'else', 'console', 'log'];
tokens = tokens.map(function (token) {
if (keywords.includes(token)) {
return `<span class="keyword">${token}</span>`;
} else if (/[\+\-\*\/=]/.test(token)) {
return `<span class="operator">${token}</span>`;
}
return token;
});
codeElement.innerHTML = tokens.join('');
});
</script>
</body>
</html>
Output:
OutputConclusion
Each approach to creating a syntax highlighter has its strengths and trade-offs. For simple projects, regular expressions might be sufficient. For more complex needs, tokenization offers better control, while libraries like Prism.js or Highlight.js are best for comprehensive and easy-to-use solutions.
Similar Reads
How to Create a Style Tag using JavaScript? To create a <style> tag using JavaScript, use the document.createElement() method to create the tag, which allows you to dynamically add elements to the DOM.Syntaxdocument.createElement('style')Example 1: This HTML code dynamically styles a <div> element with a green background and white
1 min read
How to create a Color Generator using HTML CSS and JavaScript ? In this article, we will develop a Color Generator application using HTML, CSS, and JavaScript.In this application, we have created the Multi Format color generator. Users can select Colour Types like RGB, HEX, and CMYK. Use the sliders to customize the color and Inout field in case of HEX and color
6 min read
How to Add Text Formatting to a Textarea using JavaScript? To add text formatting (such as bold, italic, or inserting special characters) to a <textarea> using JavaScript, you can manipulate the selected text or insert formatted text at the cursor position. This can be done by directly modifying the value of the <textarea> based on user interact
3 min read
How to highlight syntax in files using Node.js ? Node.js supports modules and packages that can be installed using NPM, which allows us to exploit various functionalities. One such functionality is syntax highlighting using Node.js that helps us to render highlighted code as static HTML, or we can also use it for dynamic syntax highlighting. The f
2 min read
How to create an element from a string in JavaScript ? In this article, we will learn how to create an element from a string using JavaScript. This can be used in situations where dynamically generated elements are required by the user. This can be achieved using many approaches as given below: Table of Content Using the createElement() methodUsing the
3 min read
How to Highlight the Searched String Result using JavaScript ? Given below is an HTML document which is basically about how to highlight the searched string result. In this article, we are using HTML, CSS, JavaScript, Bootstrap and mark.js to make our website more effective. Moreover, exclusively for highlighting the searched string among a given context or par
4 min read
How to get the Highlighted/Selected text in JavaScript? There may be a need to find out the text selected/highlighted by the user. It can be done very easily using the window and document objects and their properties. Handling selected text is different for different browsers. The ways to get selected text are shown below: Method 1: window.getSelection p
2 min read
How to change style/class of an element using JavaScript ? In this article, we will learn how we can change the style/class of an element. If you want to build a cool website or app then UI plays an important role. We can change, add or remove any CSS property from an HTML element on the occurrence of any event with the help of JavaScript. There are two com
4 min read
How to Detect Keypress using JavaScript ? In this article, keyboard detection is performed using HTML and CSS. HTML stands for "Hypertext Markup Language". HTML language helps the developer to create and design web page elements like links, sections, paragraphs, headings, and blockquotes for web applications. CSS stands for "Cascading Style
2 min read
How to define marked/highlighted text using HTML? To define highlighted or marked text in HTML5, the <mark> tag is employed. It effectively highlights specific text within a paragraph, offering a straightforward way to visually emphasize content. Introduced in HTML5, the `<mark>` tag enhances readability and focus within web content.Syn
1 min read