-
Notifications
You must be signed in to change notification settings - Fork 0
/
html_parser.js
54 lines (50 loc) · 1.36 KB
/
html_parser.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
import parse from 'html-dom-parser'
const nonWhiteLength = (att) => {
return att.trim().length
}
const isObjectEmpty = (objectName) => {
return (
objectName &&
Object.keys(objectName).length === 0 &&
objectName.constructor === Object
)
}
const parseElement = (e) => {
let attrs = {}
let children = []
if (e.type == 'tag') {
children = (e?.children ?? Array())?.map((e) => parseElement(e))
attrs = e?.attribs ?? {}
return {
tag: e.name,
children: children.filter((i) => !isObjectEmpty(i)),
attrs: attrs,
data: e?.data,
}
} else {
if (e.type == 'directive') {
return {}
} else {
if (e.type == 'text') {
let str = e?.data ?? ''
if (nonWhiteLength(str) > 0) {
return {
tag: 'text',
children: children,
attrs: attrs,
data: str.trim(),
}
} else return {}
} else {
return {}
}
}
}
}
export function parse_html(html_str) {
let elements = parse(html_str.trim())
let _es = elements
.map((e) => parseElement(e))
.filter((i) => !isObjectEmpty(i))
return _es
}