For the ...${i}..., we should highlight anything inside of the {} as normal code rather…
- User
For the
...${i}..., we should highlight anything inside of the {} as normal code rather than a string: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", gray: "\x1b[90m", }, 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", }, };
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; }
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);
class TestElement extends HTMLElement { constructor() { super(); }
connectedCallback() { this.innerHTML = `Hey there ${i} diddy`; } }
customElements.define('test-element', TestElement); `;
console.log(highlightJS(sampleCode));
- Assistant