node package manager

he

A robust HTML entities encoder/decoder with full Unicode support.

he Build status Dependency status

he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as per HTML, handles ambiguous ampersands just like a browser would, has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine.

Installation

Via npm:

npm install he

Via Bower:

bower install he

Via Component:

component install mathiasbynens/he

In a browser:

<script src="he.js"></script>

In Narwhal, Node.js, and RingoJS:

var he = require('he');

In Rhino:

load('he.js');

Using an AMD loader like RequireJS:

require(
  {
    'paths': {
      'he': 'path/to/he'
    }
  },
  ['he'],
  function(he) {
    console.log(he);
  }
);

API

he.version

A string representing the semantic version number.

he.encode(text)

This function takes a string of text and encodes any symbols that can be replaced with named character references (e.g. ©&copy;. Additionally, it replaces any remaining non-ASCII symbols with a hexadecimal escape sequence (e.g. &#x1D306;).

he.encode('foo © bar ≠ baz 𝌆 qux');
// → 'foo &copy; bar &ne; baz &#x1D306; qux'

he.decode(html)

This function takes a string of HTML and decodes any named and numerical character references in it.

he.encode('foo &copy; bar &ne; baz &#x1D306; qux');
// → 'foo © bar ≠ baz 𝌆 qux'

he.escape(text)

This function takes a string of text and escapes it for use in text contexts in XML or HTML documents. Only the following characters are escaped: &, <, >, ", and \.

he.escape('<img src=\'x\' onerror="prompt(1)">');
// → '&lt;img src=&apos;x&apos; onerror=&quot;prompt(1)&quot;&gt;'

he.unescape(html)

he.unescape is an alias for he.decode. It takes a string of HTML and decodes any named and numerical character references in it.

Support

he has been tested in at least Chrome 27-29, Firefox 3-22, Safari 4-6, Opera 10-12, IE 6-10, Node.js v0.10.0, Narwhal 0.3.2, RingoJS 0.8-0.9, PhantomJS 1.9.0, and Rhino 1.7RC4.

Unit tests & code coverage

After cloning this repository, run npm install to install the dependencies needed for he development and testing. You may want to install Istanbul globally using npm install istanbul -g.

Once that’s done, you can run the unit tests in Node using npm test or node tests/tests.js. To run the tests in Rhino, Ringo, Narwhal, and web browsers as well, use grunt test.

To generate the code coverage report, use grunt cover.

Author

twitter/mathias
Mathias Bynens

License

he is available under the MIT license.