UNPKG

980 BJavaScriptView Raw
1'use strict';
2
3var string = require('./string');
4
5/**
6 * Escape HTML characters in a string.
7 *
8 * ```js
9 * <%= escapeHtml("<span>foo</span>") %>
10 * //=> &lt;span&gt;foo&lt;&#x2F;span&gt;
11 * ```
12 *
13 * @param {String} `str` String of HTML with characters to escape.
14 * @return {String}
15 * @api public
16 */
17
18exports.escapeHtml = function escapeHtml(str) {
19 if (!string.isString(str)) return '';
20 return str.replace(/[\/"'&<>]/g, function(ch) {
21 return ({
22 '"': '&quot;',
23 '&': '&amp;',
24 '/': '&#x2F;',
25 '<': '&lt;',
26 '>': '&gt;',
27 '\'': '&#39;'
28 })[ch];
29 });
30};
31
32/**
33 * Strip HTML tags from a string, so that only the text nodes
34 * are preserved.
35 *
36 * ```js
37 * <%= sanitize("<span>foo</span>") %>
38 * //=> 'foo'
39 * ```
40 *
41 * @param {String} `str` The string of HTML to sanitize.
42 * @return {String}
43 * @api public
44 */
45
46exports.sanitize = function sanitize(str) {
47 return string.isString(str) ? str.replace(/(<([^>]+)>)/g, '').trim() : '';
48};