JSFiddle - React, Tailwind, and code Playground

by velo_ninja

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS Syntax Highlighting</title>
    <style>
        /* Define styles for different code elements */
        .js-beautify {
            background-color: #2e3440;
            color: #d8dee9;
            padding: 10px;
            border-radius: 5px;
            font-family: 'Courier New', Courier, monospace;
            white-space: pre-wrap; /* Preserve whitespace for proper indentation */
            line-height: 1.5; /* Adjust line height for readability */
        }

        .string { color: #a3be8c; }
        .literal { color: #b48ead; }
        .number { color: #b48ead; }
        .keyword { color: #81a1c1; font-weight: bold; }
        .comment { color: #616e88; font-style: italic; }
        .function { color: #88c0d0; }
        .punctuation { color: #eceff4; }
        .line-break { display: block; margin-top: 20px; } /* Optional: Page break styling */
    </style>
</head>
<body>
    <div id="code-container"></div>

    <script>
        // Function to beautify, format, and highlight JavaScript code
        function beautifyJavaScript(code, tabSize = 4) {
            // Escape special HTML characters to prevent breaking the HTML structure
            code = code.replace(/</g, '&lt;').replace(/>/g, '&gt;');

            // Convert tabs to spaces based on the provided tabSize
            const tabSpaces = ' '.repeat(tabSize);
            code = code.replace(/\t/g, tabSpaces);

            // Define regex patterns for different types of code elements
            const patterns = [
                { regex: /(".*?"|'.*?'|`.*?`)/g, className: 'string' }, // Strings
                { regex: /\b(true|false|null|undefined)\b/g, className: 'literal' }, // Booleans and null/undefined
                { regex: /\b(\d+\.?\d*|\.\d+)\b/g, className: 'number' }, // Numbers
                { regex:...