-
Notifications
You must be signed in to change notification settings - Fork 6
/
slackify-html.js
45 lines (42 loc) · 1.06 KB
/
slackify-html.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
var htmlparser = require('htmlparser'),
Entities = require('html-entities').AllHtmlEntities;
entities = new Entities();
module.exports = function slackify(html) {
var handler = new htmlparser.DefaultHandler(function (error, dom) {
// error ignored
});
var parser = new htmlparser.Parser(handler);
parser.parseComplete(html);
var dom = handler.dom;
if (dom)
return entities.decode(walk(dom));
else
return '';
}
function walk(dom) {
var out = '';
if (dom)
dom.forEach(function (el) {
if ('text' === el.type) {
out += el.data;
}
if ('tag' === el.type) {
switch (el.name) {
case 'a':
out += '<' + el.attribs.href + '|' + walk(el.children) + '>';
break;
case 'strong':
case 'b':
out += '*' + walk(el.children) + '*';
break;
case 'i':
case 'em':
out += '_' + walk(el.children) + '_';
break;
default:
out += walk(el.children);
}
}
});
return out;
}