-
Notifications
You must be signed in to change notification settings - Fork 24
/
index.js
59 lines (53 loc) · 1.48 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
var fs = require('fs');
var entities = JSON.parse(
fs.readFileSync(__dirname + '/entities.json', 'utf8')
);
var revEntities = {};
Object.keys(entities).forEach(function (key) {
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 (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+);?/, function (_, code) {
return String.fromCharCode(code);
})
.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;
}
})
;
};