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