-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathencodeHTML.js
More file actions
34 lines (33 loc) · 840 Bytes
/
encodeHTML.js
File metadata and controls
34 lines (33 loc) · 840 Bytes
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
export const addLink = (s) => {
const reg = /((https?:\/\/[a-zA-Z0-9.\-_@:/~?%&;=+#',()*!\[\]]+))/g;
return s.replace(reg, (all, url) => `<a href="${url}">${url}</a>`);
};
export const encodeHTML = (s, withlink) => { // supported: string, array, object
if (s == null) {
return null;
}
if (Array.isArray(s)) {
return s.map(s => encodeHTML(s, withlink));
}
const t = typeof s;
if (t == "object") {
const res = {};
for (const name in s) {
const n2 = encodeHTML(name, withlink);
const v2 = encodeHTML(s[name], withlink);
res[n2] = v2;
}
return res;
}
if (s != "string") {
s = s.toString();
}
s = s.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/\n/g, "<br>");
if (withlink) {
s = addLink(s);
}
return s;
};