forked from Scimonster/wiki-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
html.js
69 lines (62 loc) · 1.76 KB
/
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// HTML data methods
var _ = require('underscore');
// Return an array where odd keys are outside the tag and even are inside
function extractTags(text, tag) {
if (_.isString(tag)) {
var openTag = '<' + tag + '[^>]*>',
closeTag = '<\/' + tag + '>',
split = text.split(new RegExp('(' + openTag + '|' + closeTag + ')')),
open = 0,
ret = [];
split.forEach(function(t, i){
if (t.match(openTag)) {
open++;
}
if (t.match(closeTag)) {
open--;
}
if (open == 0 && !t.match(closeTag)) {
ret.push(t);
if (i != split.length -1) {
ret.push('');
}
} else {
ret[ret.length - 1] += t;
}
});
return ret;
} else if (_.isArray(tag)) {
return tag.reduce(function(text, tag){
return _.flatten(text.map(function(t, i){
return i % 2 ? t : extractTags(t, tag);
}));
}, [text]);
} else {
return text;
}
}
exports.extractTags = extractTags;
// generate HTML for a tag
function createTag(tagName, attributes, textContent, opts) {
if (!_.isObject(attributes)) {
attributes = {};
}
if (!_.isObject(opts)) {
opts = {};
}
return '<' + tagName.toLowerCase() + // open tag
(Object.keys(attributes).length ? _.reduce(attributes, function(attrs, val, name){
return attrs + ' ' + name + '=' + JSON.stringify(val.toString());
}, '') : '') + (opts.selfClose ? ' />' : '>' + // attributes
(opts.escape ? _.escape(textContent) : textContent).toString().trim() + // content
'</' + tagName.toLowerCase() + '>');
}
exports.createTag = createTag;
exports.classes = function(classList) {
return _.uniq(_.compact(classList)).join(' ');
};
exports.extractAttrs = function(attrs) {
return attrs.trim() ? _.object(attrs.match(/[a-z]+\="[^"]*"/ig).map(function(attr){
return _.rest(attr.match(/([a-z]+)\="([^"]*)"/i));
})) : {};
};