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 對象,都還對應的上。