This repository has been archived by the owner on Jun 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
58 lines (51 loc) · 1.51 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
function isArray(obj) {
return Object.prototype.toString.apply(obj).slice(8, -1) == "Array";
}
/**
* Escapes HTML tags.
* @param {string} html HTML contents.
* @param {string | string[]} tags Escape specified tags, default is
* `<script><style><iframe><object><embed>`.
* @returns {string} Escaped HTML contents.
*/
function escapeTags(html, tags) {
tags = tags || "<script><style><iframe><object><embed>";
tags = isArray(tags) ? tags : tags.match(/[a-zA-Z0-9\-:]+/g);
for (var i in tags) {
var tag = tags[i],
re1 = new RegExp("<" + tag + "\\s*>", "gi"),
re2 = new RegExp("<\\/" + tag + "\\s*>", "gi"),
re3 = new RegExp("<" + tag + "(.*)>", "gi");
html = html.replace(re1, "<" + tag + ">")
.replace(re2, "</" + tag + ">")
.replace(re3, match => {
return "<" + match.substring(1, match.length - 1) + ">";
});
}
return html;
}
/**
* Escapes JavaScript hrefs.
* @param {string} html
* @returns {string}
*/
function escapeScriptHrefs(html) {
return html.replace(/\shref\s*=["'\s]*\w+script:/gi, match => {
return match.replace("href", "data-href");
});
}
/**
* Escapes event attributes.
* @param {string} html
* @returns {string}
*/
function escapeEventAttributes(html) {
return html.replace(/\son[a-z]+\s*=/gi, match => {
return " data-" + match.substring(1);
});
}
module.exports = {
escapeTags,
escapeScriptHrefs,
escapeEventAttributes
}