css-escape
Escape a string for use as a CSS identifier — a faithful implementation of the
CSSOM CSS.escape()
algorithm (the same one behind the css.escape
npm package). Turn arbitrary text into something safe to drop into a selector,
class, or id. Zero dependencies and #![no_std].
use escape;
// Safely target an element by id, whatever the id contains.
assert_eq!;
assert_eq!; // a leading digit is escaped
assert_eq!; // punctuation is backslash-escaped
assert_eq!; // non-ASCII passes through
Why css-escape?
Building a CSS selector by concatenating a user-supplied id or class is a footgun:
spaces, dots, #, leading digits, and more all break the selector (or worse). The
browser solves this with CSS.escape, but Rust had no equivalent for scrapers,
SSR, and DOM tooling. This is that one focused, spec-exact function.
[]
= "0.1"
API
| Item | Purpose |
|---|---|
escape(value) |
Escape value as a CSS identifier (CSSOM CSS.escape()) |
Behavior
- Implements the CSSOM
CSS.escape()algorithm exactly:NUL→U+FFFD; C0 controls andDEL→\<hex>; a leading digit (or a digit right after a leading-) →\<hex>; a lone-→\-;U+0080+,-,_, and ASCII alphanumerics pass through; everything else is backslash-escaped. - Escapes identifiers (selectors, class/id names). Producing a quoted CSS string value is a different operation — it must also escape newlines and control characters — and is out of scope.
no_std
#![no_std] (needs only alloc) with zero dependencies.
Contributors ✨
This project follows the all-contributors specification. Contributions of any kind are welcome — code, docs, bug reports, ideas, reviews! See the emoji key for how each contribution is recognized, and open a PR or issue to get involved.
Thanks goes to these wonderful people:
License
Licensed under either of Apache-2.0 or MIT at your option.