You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

379 lines
14 KiB

4 years ago
  1. # he [![Build status](https://travis-ci.org/mathiasbynens/he.svg?branch=master)](https://travis-ci.org/mathiasbynens/he) [![Code coverage status](https://codecov.io/github/mathiasbynens/he/coverage.svg?branch=master)](https://codecov.io/github/mathiasbynens/he?branch=master) [![Dependency status](https://gemnasium.com/mathiasbynens/he.svg)](https://gemnasium.com/mathiasbynens/he)
  2. _he_ (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports [all standardized named character references as per HTML](https://html.spec.whatwg.org/multipage/syntax.html#named-character-references), handles [ambiguous ampersands](https://mathiasbynens.be/notes/ambiguous-ampersands) and other edge cases [just like a browser would](https://html.spec.whatwg.org/multipage/syntax.html#tokenizing-character-references), has an extensive test suite, and — contrary to many other JavaScript solutions — _he_ handles astral Unicode symbols just fine. [An online demo is available.](https://mothereff.in/html-entities)
  3. ## Installation
  4. Via [npm](https://www.npmjs.com/):
  5. ```bash
  6. npm install he
  7. ```
  8. Via [Bower](http://bower.io/):
  9. ```bash
  10. bower install he
  11. ```
  12. Via [Component](https://github.com/component/component):
  13. ```bash
  14. component install mathiasbynens/he
  15. ```
  16. In a browser:
  17. ```html
  18. <script src="he.js"></script>
  19. ```
  20. In [Node.js](https://nodejs.org/), [io.js](https://iojs.org/), [Narwhal](http://narwhaljs.org/), and [RingoJS](http://ringojs.org/):
  21. ```js
  22. var he = require('he');
  23. ```
  24. In [Rhino](http://www.mozilla.org/rhino/):
  25. ```js
  26. load('he.js');
  27. ```
  28. Using an AMD loader like [RequireJS](http://requirejs.org/):
  29. ```js
  30. require(
  31. {
  32. 'paths': {
  33. 'he': 'path/to/he'
  34. }
  35. },
  36. ['he'],
  37. function(he) {
  38. console.log(he);
  39. }
  40. );
  41. ```
  42. ## API
  43. ### `he.version`
  44. A string representing the semantic version number.
  45. ### `he.encode(text, options)`
  46. This function takes a string of text and encodes (by default) any symbols that aren’t printable ASCII symbols and `&`, `<`, `>`, `"`, `'`, and `` ` ``, replacing them with character references.
  47. ```js
  48. he.encode('foo © bar ≠ baz 𝌆 qux');
  49. // → 'foo &#xA9; bar &#x2260; baz &#x1D306; qux'
  50. ```
  51. As long as the input string contains [allowed code points](https://html.spec.whatwg.org/multipage/parsing.html#preprocessing-the-input-stream) only, the return value of this function is always valid HTML. Any [(invalid) code points that cannot be represented using a character reference](https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides) in the input are not encoded:
  52. ```js
  53. he.encode('foo \0 bar');
  54. // → 'foo \0 bar'
  55. ```
  56. However, enabling [the `strict` option](https://github.com/mathiasbynens/he#strict) causes invalid code points to throw an exception. With `strict` enabled, `he.encode` either throws (if the input contains invalid code points) or returns a string of valid HTML.
  57. The `options` object is optional. It recognizes the following properties:
  58. #### `useNamedReferences`
  59. The default value for the `useNamedReferences` option is `false`. This means that `encode()` will not use any named character references (e.g. `&copy;`) in the output — hexadecimal escapes (e.g. `&#xA9;`) will be used instead. Set it to `true` to enable the use of named references.
  60. **Note that if compatibility with older browsers is a concern, this option should remain disabled.**
  61. ```js
  62. // Using the global default setting (defaults to `false`):
  63. he.encode('foo © bar ≠ baz 𝌆 qux');
  64. // → 'foo &#xA9; bar &#x2260; baz &#x1D306; qux'
  65. // Passing an `options` object to `encode`, to explicitly disallow named references:
  66. he.encode('foo © bar ≠ baz 𝌆 qux', {
  67. 'useNamedReferences': false
  68. });
  69. // → 'foo &#xA9; bar &#x2260; baz &#x1D306; qux'
  70. // Passing an `options` object to `encode`, to explicitly allow named references:
  71. he.encode('foo © bar ≠ baz 𝌆 qux', {
  72. 'useNamedReferences': true
  73. });
  74. // → 'foo &copy; bar &ne; baz &#x1D306; qux'
  75. ```
  76. #### `decimal`
  77. The default value for the `decimal` option is `false`. If the option is enabled, `encode` will generally use decimal escapes (e.g. `&#169;`) rather than hexadecimal escapes (e.g. `&#xA9;`). Beside of this replacement, the basic behavior remains the same when combined with other options. For example: if both options `useNamedReferences` and `decimal` are enabled, named references (e.g. `&copy;`) are used over decimal escapes. HTML entities without a named reference are encoded using decimal escapes.
  78. ```js
  79. // Using the global default setting (defaults to `false`):
  80. he.encode('foo © bar ≠ baz 𝌆 qux');
  81. // → 'foo &#xA9; bar &#x2260; baz &#x1D306; qux'
  82. // Passing an `options` object to `encode`, to explicitly disable decimal escapes:
  83. he.encode('foo © bar ≠ baz 𝌆 qux', {
  84. 'decimal': false
  85. });
  86. // → 'foo &#xA9; bar &#x2260; baz &#x1D306; qux'
  87. // Passing an `options` object to `encode`, to explicitly enable decimal escapes:
  88. he.encode('foo © bar ≠ baz 𝌆 qux', {
  89. 'decimal': true
  90. });
  91. // → 'foo &#169; bar &#8800; baz &#119558; qux'
  92. // Passing an `options` object to `encode`, to explicitly allow named references and decimal escapes:
  93. he.encode('foo © bar ≠ baz 𝌆 qux', {
  94. 'useNamedReferences': true,
  95. 'decimal': true
  96. });
  97. // → 'foo &copy; bar &ne; baz &#119558; qux'
  98. ```
  99. #### `encodeEverything`
  100. The default value for the `encodeEverything` option is `false`. This means that `encode()` will not use any character references for printable ASCII symbols that don’t need escaping. Set it to `true` to encode every symbol in the input string. When set to `true`, this option takes precedence over `allowUnsafeSymbols` (i.e. setting the latter to `true` in such a case has no effect).
  101. ```js
  102. // Using the global default setting (defaults to `false`):
  103. he.encode('foo © bar ≠ baz 𝌆 qux');
  104. // → 'foo &#xA9; bar &#x2260; baz &#x1D306; qux'
  105. // Passing an `options` object to `encode`, to explicitly encode all symbols:
  106. he.encode('foo © bar ≠ baz 𝌆 qux', {
  107. 'encodeEverything': true
  108. });
  109. // → '&#x66;&#x6F;&#x6F;&#x20;&#xA9;&#x20;&#x62;&#x61;&#x72;&#x20;&#x2260;&#x20;&#x62;&#x61;&#x7A;&#x20;&#x1D306;&#x20;&#x71;&#x75;&#x78;'
  110. // This setting can be combined with the `useNamedReferences` option:
  111. he.encode('foo © bar ≠ baz 𝌆 qux', {
  112. 'encodeEverything': true,
  113. 'useNamedReferences': true
  114. });
  115. // → '&#x66;&#x6F;&#x6F;&#x20;&copy;&#x20;&#x62;&#x61;&#x72;&#x20;&ne;&#x20;&#x62;&#x61;&#x7A;&#x20;&#x1D306;&#x20;&#x71;&#x75;&#x78;'
  116. ```
  117. #### `strict`
  118. The default value for the `strict` option is `false`. This means that `encode()` will encode any HTML text content you feed it, even if it contains any symbols that cause [parse errors](https://html.spec.whatwg.org/multipage/parsing.html#preprocessing-the-input-stream). To throw an error when such invalid HTML is encountered, set the `strict` option to `true`. This option makes it possible to use _he_ as part of HTML parsers and HTML validators.
  119. ```js
  120. // Using the global default setting (defaults to `false`, i.e. error-tolerant mode):
  121. he.encode('\x01');
  122. // → '&#x1;'
  123. // Passing an `options` object to `encode`, to explicitly enable error-tolerant mode:
  124. he.encode('\x01', {
  125. 'strict': false
  126. });
  127. // → '&#x1;'
  128. // Passing an `options` object to `encode`, to explicitly enable strict mode:
  129. he.encode('\x01', {
  130. 'strict': true
  131. });
  132. // → Parse error
  133. ```
  134. #### `allowUnsafeSymbols`
  135. The default value for the `allowUnsafeSymbols` option is `false`. This means that characters that are unsafe for use in HTML content (`&`, `<`, `>`, `"`, `'`, and `` ` ``) will be encoded. When set to `true`, only non-ASCII characters will be encoded. If the `encodeEverything` option is set to `true`, this option will be ignored.
  136. ```js
  137. he.encode('foo © and & ampersand', {
  138. 'allowUnsafeSymbols': true
  139. });
  140. // → 'foo &#xA9; and & ampersand'
  141. ```
  142. #### Overriding default `encode` options globally
  143. The global default setting can be overridden by modifying the `he.encode.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.
  144. ```js
  145. // Read the global default setting:
  146. he.encode.options.useNamedReferences;
  147. // → `false` by default
  148. // Override the global default setting:
  149. he.encode.options.useNamedReferences = true;
  150. // Using the global default setting, which is now `true`:
  151. he.encode('foo © bar ≠ baz 𝌆 qux');
  152. // → 'foo &copy; bar &ne; baz &#x1D306; qux'
  153. ```
  154. ### `he.decode(html, options)`
  155. This function takes a string of HTML and decodes any named and numerical character references in it using [the algorithm described in section 12.2.4.69 of the HTML spec](https://html.spec.whatwg.org/multipage/syntax.html#tokenizing-character-references).
  156. ```js
  157. he.decode('foo &copy; bar &ne; baz &#x1D306; qux');
  158. // → 'foo © bar ≠ baz 𝌆 qux'
  159. ```
  160. The `options` object is optional. It recognizes the following properties:
  161. #### `isAttributeValue`
  162. The default value for the `isAttributeValue` option is `false`. This means that `decode()` will decode the string as if it were used in [a text context in an HTML document](https://html.spec.whatwg.org/multipage/syntax.html#data-state). HTML has different rules for [parsing character references in attribute values](https://html.spec.whatwg.org/multipage/syntax.html#character-reference-in-attribute-value-state) — set this option to `true` to treat the input string as if it were used as an attribute value.
  163. ```js
  164. // Using the global default setting (defaults to `false`, i.e. HTML text context):
  165. he.decode('foo&ampbar');
  166. // → 'foo&bar'
  167. // Passing an `options` object to `decode`, to explicitly assume an HTML text context:
  168. he.decode('foo&ampbar', {
  169. 'isAttributeValue': false
  170. });
  171. // → 'foo&bar'
  172. // Passing an `options` object to `decode`, to explicitly assume an HTML attribute value context:
  173. he.decode('foo&ampbar', {
  174. 'isAttributeValue': true
  175. });
  176. // → 'foo&ampbar'
  177. ```
  178. #### `strict`
  179. The default value for the `strict` option is `false`. This means that `decode()` will decode any HTML text content you feed it, even if it contains any entities that cause [parse errors](https://html.spec.whatwg.org/multipage/syntax.html#tokenizing-character-references). To throw an error when such invalid HTML is encountered, set the `strict` option to `true`. This option makes it possible to use _he_ as part of HTML parsers and HTML validators.
  180. ```js
  181. // Using the global default setting (defaults to `false`, i.e. error-tolerant mode):
  182. he.decode('foo&ampbar');
  183. // → 'foo&bar'
  184. // Passing an `options` object to `decode`, to explicitly enable error-tolerant mode:
  185. he.decode('foo&ampbar', {
  186. 'strict': false
  187. });
  188. // → 'foo&bar'
  189. // Passing an `options` object to `decode`, to explicitly enable strict mode:
  190. he.decode('foo&ampbar', {
  191. 'strict': true
  192. });
  193. // → Parse error
  194. ```
  195. #### Overriding default `decode` options globally
  196. The global default settings for the `decode` function can be overridden by modifying the `he.decode.options` object. This saves you from passing in an `options` object for every call to `decode` if you want to use a non-default setting.
  197. ```js
  198. // Read the global default setting:
  199. he.decode.options.isAttributeValue;
  200. // → `false` by default
  201. // Override the global default setting:
  202. he.decode.options.isAttributeValue = true;
  203. // Using the global default setting, which is now `true`:
  204. he.decode('foo&ampbar');
  205. // → 'foo&ampbar'
  206. ```
  207. ### `he.escape(text)`
  208. 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 `` ` ``.
  209. ```js
  210. he.escape('<img src=\'x\' onerror="prompt(1)">');
  211. // → '&lt;img src=&#x27;x&#x27; onerror=&quot;prompt(1)&quot;&gt;'
  212. ```
  213. ### `he.unescape(html, options)`
  214. `he.unescape` is an alias for `he.decode`. It takes a string of HTML and decodes any named and numerical character references in it.
  215. ### Using the `he` binary
  216. To use the `he` binary in your shell, simply install _he_ globally using npm:
  217. ```bash
  218. npm install -g he
  219. ```
  220. After that you will be able to encode/decode HTML entities from the command line:
  221. ```bash
  222. $ he --encode 'föo ♥ bår 𝌆 baz'
  223. f&#xF6;o &#x2665; b&#xE5;r &#x1D306; baz
  224. $ he --encode --use-named-refs 'föo ♥ bår 𝌆 baz'
  225. f&ouml;o &hearts; b&aring;r &#x1D306; baz
  226. $ he --decode 'f&ouml;o &hearts; b&aring;r &#x1D306; baz'
  227. föo ♥ bår 𝌆 baz
  228. ```
  229. Read a local text file, encode it for use in an HTML text context, and save the result to a new file:
  230. ```bash
  231. $ he --encode < foo.txt > foo-escaped.html
  232. ```
  233. Or do the same with an online text file:
  234. ```bash
  235. $ curl -sL "http://git.io/HnfEaw" | he --encode > escaped.html
  236. ```
  237. Or, the opposite — read a local file containing a snippet of HTML in a text context, decode it back to plain text, and save the result to a new file:
  238. ```bash
  239. $ he --decode < foo-escaped.html > foo.txt
  240. ```
  241. Or do the same with an online HTML snippet:
  242. ```bash
  243. $ curl -sL "http://git.io/HnfEaw" | he --decode > decoded.txt
  244. ```
  245. See `he --help` for the full list of options.
  246. ## Support
  247. _he_ has been tested in at least:
  248. * Chrome 27-50
  249. * Firefox 3-45
  250. * Safari 4-9
  251. * Opera 10-12, 15–37
  252. * IE 6–11
  253. * Edge
  254. * Narwhal 0.3.2
  255. * Node.js v0.10, v0.12, v4, v5
  256. * PhantomJS 1.9.0
  257. * Rhino 1.7RC4
  258. * RingoJS 0.8-0.11
  259. ## Unit tests & code coverage
  260. 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`.
  261. 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`.
  262. To generate the code coverage report, use `grunt cover`.
  263. ## Acknowledgements
  264. Thanks to [Simon Pieters](https://simon.html5.org/) ([@zcorpan](https://twitter.com/zcorpan)) for the many suggestions.
  265. ## Author
  266. | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
  267. |---|
  268. | [Mathias Bynens](https://mathiasbynens.be/) |
  269. ## License
  270. _he_ is available under the [MIT](https://mths.be/mit) license.