{property}</span>`;
}
if (value !== undefined) {
if (/^-?\d+(\.\d+)?(\w*)?/.test(value)) {
return `: <span class="number">
; } if (/^(#\d{3,6}|rgba?\(\d+,\s*\d+,\s*\d+(,\s*\d+(\.\d+))?\)|hsla?\(\d+,\s*\d+%,\s*\d+%(,\s*\d+(\.\d+))?\))/.test(value)) { return
{value}</span>`;
}
if (/^('|")(.*?)('|")/.test(value)) {
return `: <span class="string">
; } return
code
return match;
});
element.innerHTML = highlighted;
}
const pre = document.querySelector('pre');
highlightCSS(pre);
It looks like you're working on a function to syntax highlight CSS code within a <pre> element by wrapping different parts of the code (selectors, properties, values, etc.) with <span> tags that have specific classes for styling.
You've made a good start, but there are a few issues and potential improvements to consider. I'll walk through your code, point out some problems, and suggest how you might fix them.
Overview of Your Code
Here's a brief summary of what your code is doing:
Extracting the code: You get the CSS code from element.textContent.
Defining a regex pattern: You use a regex to match selectors, properties, and values.
Replacing matched patterns: You use code.replace() with a function that wraps matched parts in <span> tags.
Updating the element's HTML: You set element.innerHTML to the highlighted code.
Selectors Matching: The pattern (.+?)(?=\s*{) is too broad and can match unintended text, especially if there are nested blocks or comments.
Properties Matching: The pattern ([\w-]+)(?=:) doesn't account for properties that might have vendor prefixes or special characters.
Values Matching: The pattern :\s*(.*?)(?=;) can fail with values that contain ; before the actual semicolon ending the declaration (e.g., URLs with query parameters).
2. Handling Attribute Selectors and Pseudo-classes
Your code for handling attribute selectors:
javascript
if (/\[(.*?)\]/.test(selector)) {
const attrs = selector.split('[').map(attr => attr.replace(/^(.)/, '[$1'));
const word = attrs[0].slice(1);
attrs.shift();
return `<span class="selector">${word}<span class="attrs">${attrs.join('')}</span></span>`;
}
Problems:
Splitting on [: If the selector contains multiple attribute selectors or [ characters, splitting on [ can produce incorrect results.
Assuming Structure: The code assumes a certain structure of selectors which might not hold true for complex selectors.
Modification Logic: The way you're manipulating the attrs array and rebuilding the selector can lead to errors.
3. Non-standard CSS Parsing
CSS is a complex language with many edge cases. Parsing CSS with regular expressions can lead to problems because regex is not equipped to handle nested structures and all variations of CSS syntax.
Suggestions for Improvement
1. Use a Proper CSS Parser
Instead of using regular expressions to parse CSS, it's better to use a dedicated CSS parser library like PostCSS or css-tree. These parsers can correctly handle all CSS syntax, including nested rules, media queries, and so on.
However, if you prefer to stick with regex and direct string manipulation for simplicity, consider the following changes.
2. Improve the Regex Patterns
Selectors:
Match selectors more accurately by stopping at the { character and allowing for possible nested braces.
javascript
const selectorRegex = /([^{]+)\{/g;
Properties and Values:
Match properties and values within the braces:
javascript
const propertyRegex = /([\w-]+)\s*:\s*([^;]+);/g;
This pattern matches the property names and their values, capturing everything between : and ;.
3. Revise the Highlighting Function
Here's how you might rewrite your highlightCSS function:
javascript
function highlightCSS(element) {
let code = element.textContent;
// Highlight selectors
code = code.replace(/([^{]+)\{/g, (match, selector) => {
return `<span class="selector">${selector.trim()}</span>{`;
});
// Highlight properties and values
code = code.replace(/([\w-]+)\s*:\s*([^;]+);/g, (match, property, value) => {
let valueClass = 'value';
// Determine the class for the value
const trimmedValue = value.trim();
if (/^-?\d+(\.\d+)?(px|em|rem|%|vh|vw|vmin|vmax)?$/.test(trimmedValue)) {
valueClass = 'number';
} else if (/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(trimmedValue) || /^rgba?\(.*\)$/.test(trimmedValue) || /^hsla?\(.*\)$/.test(trimmedValue)) {
valueClass = 'color';
} else if (/^['"].*['"]$/.test(trimmedValue)) {
valueClass = 'string';
}
return `<span class="property">${property.trim()}</span>: <span class="${valueClass}">${trimmedValue}</span>;`;
});
element.innerHTML = code;
}
Explanation:
Selectors: We match any character(s) before a { that is not a { (to avoid overmatching) and wrap it with a <span>.
Properties and Values: We match property-value pairs and decide what class to apply to the value based on its content.
4. Handle Edge Cases
Make sure to account for:
Comments: Remove comments before processing or handle them separately.
Nested Rules: If your CSS includes nested rules (e.g., media queries), you need to handle them appropriately.
Import Statements and At-rules: Handle @import, @media, and other at-rules.
Multiple Selectors: Handle selectors that are grouped with commas.
5. Testing
Test your highlighter with various CSS snippets to ensure it works correctly:
Simple Rules:
css
body {
margin: 0;
padding: 0;
}
Complex Selectors:
css
ul li:first-child > a:hover {
color: red;
}
Attribute Selectors:
css
input[type="text"] {
border: 1px solid #ccc;
}
Media Queries:
css
@media screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
Comments and Special Characters:
css
/* This is a comment */
a[href^="https"]::after {
content: '🔒';
}
Final Thoughts
While regular expressions can work for simple syntax highlighting, they can become unwieldy for complex languages like CSS. Consider using a syntax highlighter library or a parser for more robust handling.
Here are some libraries that you might find useful:
Highlight.js: Supports many languages out of the box. Highlight.js
Codemirror: Versatile text editor implemented in JavaScript for the browser. CodeMirror
These libraries handle the parsing and highlighting for you and are optimized for performance and accuracy.
Example Using Prism.js
If you choose to use Prism.js, your code can be as simple as:
html
<!-- Include Prism.css and Prism.js from CDN or local files -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<!-- Include the CSS language syntax -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-css.min.js"></script>
<!-- Your code block -->
<pre><code class="language-css">
body {
margin: 0;
padding: 0;
}
</code></pre>
Prism.js will automatically detect the language-css class on the <code> element and apply syntax highlighting.
I hope this helps you improve your CSS syntax highlighter!