UNPKG

1.66 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'
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, '&lt;').replace(QT_REGEX, '&gt;');
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