UNPKG

1.47 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const HTML_REGEX = /&(?!#?[a-zA-Z0-9]+;)/g;
7const LT_REGEX = /</g;
8const QT_REGEX = />/g;
9const DOUBLE_QUOTE_REGEX = /"/g;
10const SINGLE_QUOTE_REGEX = /'/g;
11const REGEX = /[\-\[\]\/{}()*+?.\\^$|]/g;
12
13module.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, '&amp;')
23 .replace(LT_REGEX, '&lt;')
24 .replace(QT_REGEX, '&gt;')
25 .replace(SINGLE_QUOTE_REGEX, '&#39;')
26 .replace(DOUBLE_QUOTE_REGEX, '&quot;');
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, '&lt;').replace(QT_REGEX, '&gt;') : '';
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