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'
|
31 | ? text.replace(REGEX, "\\$&")
|
32 | : text instanceof RegExp ? text : '';
|
33 | }
|
34 |
|
35 | static escapeTags (text) {
|
36 | if (text === '' || text === null || text === undefined) {
|
37 | return '';
|
38 | }
|
39 | if (typeof text !== 'string') {
|
40 | text = text.toString ? text.toString() : String(text);
|
41 | }
|
42 | return text.replace(LT_REGEX, '<').replace(QT_REGEX, '>');
|
43 | }
|
44 |
|
45 | static toRegex (value) {
|
46 | if (value instanceof RegExp) {
|
47 | return value;
|
48 | }
|
49 | value = this.escapeRegex(value);
|
50 | value = value.charAt(0) === '%' ? value.substring(1) : `^${value}`;
|
51 | value = value.charAt(value.length - 1) === '%' ? value.substring(0, value.length - 1) : `${value}$`;
|
52 | return new RegExp(value, 'i');
|
53 | }
|
54 | }; |
\ | No newline at end of file |