1 | ;
|
2 |
|
3 | var string = require('./string');
|
4 |
|
5 | /**
|
6 | * Escape HTML characters in a string.
|
7 | *
|
8 | * ```js
|
9 | * <%= escapeHtml("<span>foo</span>") %>
|
10 | * //=> <span>foo</span>
|
11 | * ```
|
12 | *
|
13 | * @param {String} `str` String of HTML with characters to escape.
|
14 | * @return {String}
|
15 | * @api public
|
16 | */
|
17 |
|
18 | exports.escapeHtml = function escapeHtml(str) {
|
19 | if (!string.isString(str)) return '';
|
20 | return str.replace(/[\/"'&<>]/g, function(ch) {
|
21 | return ({
|
22 | '"': '"',
|
23 | '&': '&',
|
24 | '/': '/',
|
25 | '<': '<',
|
26 | '>': '>',
|
27 | '\'': '''
|
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 |
|
46 | exports.sanitize = function sanitize(str) {
|
47 | return string.isString(str) ? str.replace(/(<([^>]+)>)/g, '').trim() : '';
|
48 | };
|