css-escape 0.1.1

Escape a string for use as a CSS identifier — the CSSOM CSS.escape() algorithm. Zero dependencies, no_std.
Documentation
  • Coverage
  • 100%
    2 out of 2 items documented2 out of 2 items with examples
  • Size
  • Source code size: 24.9 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 29.7 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 2s Average build duration of successful builds.
  • all releases: 3s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • trananhtung/css-escape
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • trananhtung

css-escape

All Contributors

Crates.io Documentation CI License

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 css_escape::escape;

// Safely target an element by id, whatever the id contains.
assert_eq!(format!("#{}", escape("a b#c")), "#a\\ b\\#c");

assert_eq!(escape("0first"), "\\30 first"); // a leading digit is escaped
assert_eq!(escape(".foo"), "\\.foo");        // punctuation is backslash-escaped
assert_eq!(escape("café"), "café");           // 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.

[dependencies]
css-escape = "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 and DEL → \<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.