1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const HTML_REGEX = /&(?!#?[a-zA-Z0-9]+;)/g;
|
7 | const LT_REGEX = /</g;
|
8 | const QT_REGEX = />/g;
|
9 | const DOUBLE_QUOTE_REGEX = /"/g;
|
10 | const SINGLE_QUOTE_REGEX = /'/g;
|
11 | const REGEX = /[\-\[\]\/{}()*+?.\\^$|]/g;
|
12 |
|
13 | module.exports = class EscapeHelper {
|
14 |
|
15 | static escapeHtml (text) {
|
16 | if (!text) {
|
17 | return '';
|
18 | }
|
19 | if (typeof text !== 'string') {
|
20 | text = String(text);
|
21 | }
|
22 | return text.replace(HTML_REGEX, '&')
|
23 | .replace(LT_REGEX, '<')
|
24 | .replace(QT_REGEX, '>')
|
25 | .replace(SINGLE_QUOTE_REGEX, ''')
|
26 | .replace(DOUBLE_QUOTE_REGEX, '"');
|
27 | }
|
28 |
|
29 | static escapeRegex (text) {
|
30 | return typeof text === 'string' ? text.replace(REGEX, "\\$&") : '';
|
31 | }
|
32 |
|
33 | static escapeTags (text) {
|
34 | text = text && typeof text !== 'string' ? String(text) : text;
|
35 | return text ? text.replace(LT_REGEX, '<').replace(QT_REGEX, '>') : '';
|
36 | }
|
37 |
|
38 | static toRegex (value) {
|
39 | if (value instanceof RegExp) {
|
40 | return value;
|
41 | }
|
42 | value = this.escapeRegex(value);
|
43 | value = value.charAt(0) === '%' ? value.substring(1) : `^${value}`;
|
44 | value = value.charAt(value.length - 1) === '%' ? value.substring(0, value.length - 1) : `${value}$`;
|
45 | return new RegExp(value, 'i');
|
46 | }
|
47 | }; |
\ | No newline at end of file |