body { content: escape('I ♥ Sass', $is-identifier: true);}
API
cssesc(value, options)
This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) escape sequences for use in CSS strings or identifiers.
By default, cssesc returns a string that can be used as part of a CSS string. If the target is a CSS identifier rather than a CSS string, use the isIdentifier: true setting (see below).
The optional options argument accepts an object with the following options:
isIdentifier
The default value for the isIdentifier option is false. This means that the input text will be escaped for use in a CSS string literal. If you want to use the result as a CSS identifier instead (in a selector, for example), set this option to true.
The default value for the quotes option is 'single'. This means that any occurences of ' in the input text will be escaped as \', so that the output can be used in a CSS string literal wrapped in single quotes.
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.');// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'// → "Lorem ipsum \"dolor\" sit \\'amet\\' etc."cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'single'});// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.'// → "Lorem ipsum \"dolor\" sit \\'amet\\' etc."
If you want to use the output as part of a CSS string literal wrapped in double quotes, set the quotes option to 'double'.
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'double'});// → 'Lorem ipsum \\"dolor\\" sit \'amet\' etc.'// → "Lorem ipsum \\\"dolor\\\" sit 'amet' etc."
wrap
The wrap option takes a boolean value (true or false), and defaults to false (disabled). When enabled, the output will be a valid CSS string literal wrapped in quotes. The type of quotes can be specified through the quotes setting.
cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'single', 'wrap': true});// → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\''// → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'"cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'double', 'wrap': true});// → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."'// → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\""
escapeEverything
The escapeEverything option takes a boolean value (true or false), and defaults to false (disabled). When enabled, all the symbols in the output will be escaped, even printable ASCII symbols.
The global default settings can be overridden by modifying the css.options object. This saves you from passing in an options object for every call to encode if you want to use the non-default setting.
This library supports the Node.js and browser versions mentioned in .babelrc. For a version that supports a wider variety of legacy browsers and environments out-of-the-box, see v0.1.0.