const replaceAttribute = (html: string): string => {
return html.replace(attrReplaceReg, v => {
return v
.replace(ltReg, '<')
.replace(gtReg, '>')
.replace(sqAttrReg, v => {
return v.replace(qReg, '"')
})
.replace(qAttrReg, v => {
return v.replace(sqReg, ''')
})
})
}
;`<div id="container">
<div class="test" data-html="<p>hello 1</p>">
<p>hello 2</p>
<input type="text" value="hello 3" >
</div>
</div>`
["<div id="container">", "<div class="test" data-html="<p>hello 1</p>">", "<p>", "hello 2", "</p>", "<input type="text" value="hello 3" >", "</div>", "</div>"]
// 单标签集合
var singleTags = [
'img',
'input',
'br',
'hr',
'meta',
'link',
'param',
'base',
'basefont',
'area',
'source',
'track',
'embed'
]
// 其中 DomUtil 是根据 nodejs 仍是 browser 环境生成 js 对象/ dom 对象的函数
var makeUpTree = function(arr) {
var root = DomUtil('container')
var deep = 0
var parentElements = [root]
arr.forEach(function(i) {
var parentElement = parentElements[parentElements.length - 1]
if (parentElement) {
var inlineI = toOneLine(i)
// 开标签处理,新增个开标签标记
if (startReg.test(inlineI)) {
deep++
var tagName = i.match(tagCheckReg)
if (!tagName) {
throw Error('标签规范错误')
}
var element_1 = DomUtil(tagName[0])
var attrs = matchAttr(i)
attrs.forEach(function(attr) {
if (element_1) {
element_1.setAttribute(attr[0], attr[1])
}
})
parentElement.appendChild(element_1)
// 单标签处理,deep--,完成一次闭合标记
if (
singleTags.indexOf(tagName[0]) > -1 ||
i.charAt(i.length - 2) === '/'
) {
deep--
} else {
parentElements.push(element_1)
}
}
// 闭合标签处理
else if (endReg.test(inlineI)) {
deep--
parentElements.pop()
} else if (commentReg.test(inlineI)) {
var matchValue = i.match(commentReg)
var comment = matchValue ? matchValue[0] : ''
deep++
var element = DomUtil('comment', comment)
parentElement.appendChild(element)
deep--
} else {
deep++
var textElement = DomUtil('text', i)
parentElement.appendChild(textElement)
deep--
}
}
})
if (deep < 0) {
throw Error('存在多余闭合标签')
} else if (deep > 0) {
throw Error('存在多余开标签')
}
return root.children
}
[
{
attrs: {
id: 'container'
},
parentElement: [DomElement],
children: [
{
attrs: {
class: 'test',
'data-html': '<p>hello 1</p>'
},
parentElement: [DomElement],
children: [
{
attrs: {},
parentElement: [DomElement],
children: [
{
attrs: {},
parentElement: [DomElement],
children: [],
tagName: 'text',
data: 'hello 2'
}
],
tagName: 'p'
},
{
attrs: {
type: 'text',
value: 'hello 3'
},
parentElement: [DomElement],
children: [],
tagName: 'input'
}
],
tagName: 'div'
}
],
tagName: 'div'
}
]
const Parser = (html: string) => {
const htmlAfterAttrsReplace = replaceAttribute(html)
const stringArray = convertStringToArray(htmlAfterAttrsReplace)
const domTree = makeUpTree(stringArray)
return domTree
}
把 tuya / taobao / baidu / jd / tx 的首页或者新闻页都拷贝了 html 试了一波,基本在 `100ms` 内执行完,而且 dom 数量大概在几千的样子,对比了一番, html 字符串上的标签属性和对象的 attrs 对象,都还对应的上。