escapeCss
import { escapeCss } from "jsr:@ende/html/unstable-escape-css";function ยท experimental
function escapeCss(str: string): stringEscapes a string for direct interpolation into an external
CSS style sheet, within a <style> element, or in a selector.
Uses identical logic to
CSS.escape
in browsers.
str: stringThe string to escape.
Returns
The escaped string.
Example: Usage
import { escapeCss } from "@ende/html/unstable-escape-css";
import { assertEquals } from "@ende/assert";
// Invalid in a CSS selector, even though it's a valid HTML ID
const elementId = "123";
// Unsafe for interpolation
const contentInput = `<!-- '" --></style>`;
const selector = `#${escapeCss(elementId)}`;
const content = `"${escapeCss(contentInput)}"`;
// Usable as a CSS selector
assertEquals(selector, String.raw`#\31 23`);
// Safe for interpolation
assertEquals(content, String.raw`"\<\!--\ \'\"\ --\>\<\/style\>"`);
// Usage
`<style>
${selector}::after {
content: ${content};
}
</style>`;