jsesc 0.1.0

Escape a string for safe embedding in JavaScript or JSON source. A faithful port of the jsesc npm package's string escaping. Zero deps, no_std.
Documentation
  • Coverage
  • 100%
    17 out of 17 items documented2 out of 14 items with examples
  • Size
  • Source code size: 32.7 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 278.38 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 1s Average build duration of successful builds.
  • all releases: 1s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • trananhtung/jsesc
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • trananhtung

jsesc

All Contributors

crates.io docs.rs CI license

Escape a string for safe embedding in JavaScript or JSON source.

Handles quotes, backslashes, control characters, line/paragraph separators (U+2028 / U+2029), and — optionally — every non-ASCII character. A faithful Rust port of the string escaping of the widely-used jsesc npm package by Mathias Bynens.

  • Zero dependencies, #![no_std]
  • Single / double / backtick quotes, wrapping, JSON mode, ES6 unicode escapes, ASCII-only output, minimal escaping, and <script>-context safety
  • Differential-tested against the reference jsesc implementation (60k cases, all options)

Install

[dependencies]
jsesc = "0.1"

Usage

use jsesc::{jsesc, jsesc_with, Options, Quotes};

assert_eq!(jsesc("café"), "caf\\xE9");
assert_eq!(jsesc("foo'bar"), "foo\\'bar");

// JSON-safe (double quotes, wrapped, \uXXXX escapes):
assert_eq!(jsesc_with("hi", &Options::new().json(true)), "\"hi\"");

// ASCII-only output, ES6 astral escapes, backtick quotes:
assert_eq!(jsesc_with("Ā", &Options::new().escape_everything(true)), "\\u0100");
assert_eq!(jsesc_with("\u{1D306}", &Options::new().es6(true)), "\\u{1D306}");
assert_eq!(jsesc_with("`${x}`", &Options::new().quotes(Quotes::Backtick)), "\\`\\${x}\\`");

Scope

This crate ports jsesc's string escaping, which is its primary use. The npm package can also serialize numbers, arrays, and objects; for that, use serde_json.

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 MIT or Apache-2.0 at your option.