forked from slickplaid/node-ent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (56 loc) · 1.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
var entities = require('./entities.json');
var revEntities = {};
for (var key in entities) {
var e = entities[key];
var s = typeof e === 'number' ? String.fromCharCode(e) : e;
revEntities[s] = key;
}
exports.encode = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a String');
}
return str.split('').map(function (c) {
var e = revEntities[c];
var cc = c.charCodeAt(0);
if (e) {
return '&' + (e.match(/;$/) ? e : e + ';');
}
else if (c.match(/\s/)) {
return c;
}
else if (cc < 32 || cc >= 127) {
return '&#' + cc + ';';
}
else {
return c;
}
}).join('');
};
exports.decode = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a String');
}
return str
.replace(/&#(\d+);?/g, function (_, code) {
return String.fromCharCode(code);
})
.replace(/&#[xX]([A-Fa-f0-9]+);?/g, function (_, hex) {
return String.fromCharCode(parseInt(hex, 16));
})
.replace(/&([^;\W]+;?)/g, function (m, e) {
var ee = e.replace(/;$/, '');
var target = entities[e]
|| (e.match(/;$/) && entities[ee])
;
if (typeof target === 'number') {
return String.fromCharCode(target);
}
else if (typeof target === 'string') {
return target;
}
else {
return m;
}
})
;
};