-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathencoding-tools.js
47 lines (46 loc) · 1.21 KB
/
encoding-tools.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
export function findNonUtf8(text) {
const nonUtf = [];
for (let i = 0; i < text.length; i++) {
let charCode = text.charCodeAt(i);
if (charCode > 255) {
nonUtf.push({
charCode: charCode,
index: i,
char: text[i]
});
}
}
return nonUtf;
}
export function htmlEncode(text) {
let encodedText = text;
for (let i = 0; i < text.length; i++) {
const charCode = text.charCodeAt(i);
if (charCode > 255) {
encodedText = encodedText.replaceAll(text[i], "&#" + charCode + ";");
}
}
return encodedText;
}
export function htmlDecode(text){
return text.replace(/&(.*?);/g, match => {
match = match.substr(1).slice(0, -1);
switch(match){
case "lt" : return "<";
case "gt" : return ">";
case "mdash": return "—";
case "ndash": return "–";
case "amp": return "&";
case "quot": return "'";
default: {
if(match.startsWith("#x")){
return String.fromCharCode(parseInt(match.substr(2), 16));
} else if (match.startsWith("#")){
return String.fromCharCode(parseInt(match.substr(1),10));
} else {
throw new Error(`Unknown HTML entity: ${match}`);
}
}
}
});
}