Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81154 views
1
// Declare internals
2
3
var internals = {};
4
5
6
exports.escapeJavaScript = function (input) {
7
8
if (!input) {
9
return '';
10
}
11
12
var escaped = '';
13
14
for (var i = 0, il = input.length; i < il; ++i) {
15
16
var charCode = input.charCodeAt(i);
17
18
if (internals.isSafe(charCode)) {
19
escaped += input[i];
20
}
21
else {
22
escaped += internals.escapeJavaScriptChar(charCode);
23
}
24
}
25
26
return escaped;
27
};
28
29
30
exports.escapeHtml = function (input) {
31
32
if (!input) {
33
return '';
34
}
35
36
var escaped = '';
37
38
for (var i = 0, il = input.length; i < il; ++i) {
39
40
var charCode = input.charCodeAt(i);
41
42
if (internals.isSafe(charCode)) {
43
escaped += input[i];
44
}
45
else {
46
escaped += internals.escapeHtmlChar(charCode);
47
}
48
}
49
50
return escaped;
51
};
52
53
54
internals.escapeJavaScriptChar = function (charCode) {
55
56
if (charCode >= 256) {
57
return '\\u' + internals.padLeft('' + charCode, 4);
58
}
59
60
var hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');
61
return '\\x' + internals.padLeft(hexValue, 2);
62
};
63
64
65
internals.escapeHtmlChar = function (charCode) {
66
67
var namedEscape = internals.namedHtml[charCode];
68
if (typeof namedEscape !== 'undefined') {
69
return namedEscape;
70
}
71
72
if (charCode >= 256) {
73
return '&#' + charCode + ';';
74
}
75
76
var hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');
77
return '&#x' + internals.padLeft(hexValue, 2) + ';';
78
};
79
80
81
internals.padLeft = function (str, len) {
82
83
while (str.length < len) {
84
str = '0' + str;
85
}
86
87
return str;
88
};
89
90
91
internals.isSafe = function (charCode) {
92
93
return (typeof internals.safeCharCodes[charCode] !== 'undefined');
94
};
95
96
97
internals.namedHtml = {
98
'38': '&amp;',
99
'60': '&lt;',
100
'62': '&gt;',
101
'34': '&quot;',
102
'160': '&nbsp;',
103
'162': '&cent;',
104
'163': '&pound;',
105
'164': '&curren;',
106
'169': '&copy;',
107
'174': '&reg;'
108
};
109
110
111
internals.safeCharCodes = (function () {
112
113
var safe = {};
114
115
for (var i = 32; i < 123; ++i) {
116
117
if ((i >= 97) || // a-z
118
(i >= 65 && i <= 90) || // A-Z
119
(i >= 48 && i <= 57) || // 0-9
120
i === 32 || // space
121
i === 46 || // .
122
i === 44 || // ,
123
i === 45 || // -
124
i === 58 || // :
125
i === 95) { // _
126
127
safe[i] = null;
128
}
129
}
130
131
return safe;
132
}());
133
134