Write a function to highlight JavaScript syntax in console-based interface, logging the…
- User
Write a function to highlight JavaScript syntax in console-based interface, logging the code with colors...
- Assistant
Write a function to highlight JavaScript syntax in console-based interface, logging the code with colors...
To create a function that highlights JavaScript syntax in a console-based interface, you can utilize ANSI escape codes to apply colors to different parts of the code. Below is a comprehensive guide and implementation of such a function in Node.js.
First, define the ANSI escape codes for the colors you want to use. Here's a basic set of colors:
const colors = {
reset: "\x1b[0m",
bright: "\x1b[1m",
dim: "\x1b[2m",
underscore: "\x1b[4m",
blink: "\x1b[5m",
reverse: "\x1b[7m",
hidden: "\x1b[8m",
fg: {
black: "\x1b[30m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
magenta: "\x1b[35m",
cyan: "\x1b[36m",
white: "\x1b[37m",
},
bg: {
black: "\x1b[40m",
red: "\x1b[41m",
green: "\x1b[42m",
yellow: "\x1b[43m",
blue: "\x1b[44m",
magenta: "\x1b[45m",
cyan: "\x1b[46m",
white: "\x1b[47m",
},
};
Here's a function highlightJS that takes a JavaScript code string and returns it with ANSI color codes applied to various syntax elements.
function highlightJS(code) {
// Define JavaScript keywords
const keywords = [
"break",
"case",
"catch",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"export",
"extends",
"finally",
"for",
"function",
"if",
"import",
"in",
"instanceof",
"let",
"new",
"return",
"super",
"switch",
"this",
"throw",
"try",
"typeof",
"var",
"void",
"while",
"with",
"yield",
];
// Create a RegExp pattern for keywords
const keywordPattern = new RegExp(`\\b(${keywords.join("|")})\\b`, "g");
// Regex patterns for different syntax elements
const patterns = {
keyword: {
regex: keywordPattern,
color: colors.fg.blue,
},
string: {
regex: /(['"`])(\\?.)*?\1/g,
color: colors.fg.green,
},
number: {
regex: /\b(\d+(\.\d+)?)\b/g,
color: colors.fg.magenta,
},
comment: {
regex: /(\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g,
color: colors.fg.gray,
},
boolean: {
regex: /\b(true|false)\b/g,
color: colors.fg.yellow,
},
null: {
regex: /\b(null|undefined)\b/g,
color: colors.fg.yellow,
},
function: {
regex: /\b([a-zA-Z_]\w*)\s*(?=\()/g,
color: colors.fg.cyan,
},
// Add more patterns as needed
};
// Apply each pattern to the code
Object.keys(patterns).forEach((key) => {
const { regex, color } = patterns[key];
code = code.replace(regex, (match) => `${color}${match}${colors.reset}`);
});
return code;
}
Here's how you can use the highlightJS function to log highlighted JavaScript code to the console.
const sampleCode = `
// Function to add two numbers
function add(a, b) {
const sum = a + b;
return sum;
}
const result = add(5, 10);
console.log("Result:", result);
`;
console.log(highlightJS(sampleCode));
function, const, return are matched and colored blue.//) and multi-line (/* */) comments are colored gray.true, false, null, and undefined are colored yellow.To see the syntax highlighting in action:
Save the Code: Save the above code snippets into a file named highlight.js.
Run the Script: Open your terminal and navigate to the directory containing highlight.js. Execute the script using Node.js:
node highlight.js
View the Output: The JavaScript code in sampleCode will be printed to the console with colors applied to different syntax elements.
Limitations: This simple highlighter uses regular expressions, which may not cover all edge cases in JavaScript syntax. For more robust highlighting, consider using a dedicated library.
Existing Libraries: Libraries like Chalk can simplify coloring output in the console. Additionally, Prism.js and highlight.js are popular for syntax highlighting, primarily used in web environments but can be adapted for Node.js.
Performance: For large code snippets, excessive use of regular expressions and string replacements might impact performance.
If you prefer using a library to handle coloring, here's an enhanced version using Chalk:
Install Chalk:
npm install chalk
Update the Function:
const chalk = require('chalk');
function highlightJS(code) {
const keywords = [
"break", "case", "catch", "class", "const", "continue", "debugger",
"default", "delete", "do", "else", "export", "extends", "finally",
"for", "function", "if", "import", "in", "instanceof", "let", "new",
"return", "super", "switch", "this", "throw", "try", "typeof", "var",
"void", "while", "with", "yield",
];
const keywordPattern = new RegExp(`\\b(${keywords.join("|")})\\b`, "g");
const patterns = {
keyword: {
regex: keywordPattern,
formatter: chalk.blue,
},
string: {
regex: /(['"`])(\\?.)*?\1/g,
formatter: chalk.green,
},
number: {
regex: /\b(\d+(\.\d+)?)\b/g,
formatter: chalk.magenta,
},
comment: {
regex: /(\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g,
formatter: chalk.gray,
},
boolean: {
regex: /\b(true|false)\b/g,
formatter: chalk.yellow,
},
null: {
regex: /\b(null|undefined)\b/g,
formatter: chalk.yellow,
},
function: {
regex: /\b([a-zA-Z_]\w*)\s*(?=\()/g,
formatter: chalk.cyan,
},
};
Object.keys(patterns).forEach((key) => {
const { regex, formatter } = patterns[key];
code = code.replace(regex, (match) => formatter(match));
});
return code;
}
// Usage example remains the same
console.log(highlightJS(sampleCode));
Using Chalk makes the code cleaner and leverages the library's capabilities to handle colors and styles more effectively.
Creating a console-based JavaScript syntax highlighter involves identifying syntax elements, assigning colors, and applying these colors using ANSI escape codes or a library like Chalk. While the provided function offers a basic highlighting mechanism, leveraging existing libraries can provide more comprehensive and robust solutions.
Not yet included in a published release.