Open linrunzheng opened 5 years ago
function formatter(str) {
const reg = /<([a-z]+)((?:.|\n)*?)>((?:.|\n)*)<\/\1>/i
const arr = reg.exec(str)
if (!arr) return str
const [_, tag, attrsStr, childrenStr] = arr
const attrs = {}
attrsStr.replace(/([^=\s]+)="([^=]+)"/g, (_, key, value) => {
attrs[key] = value
})
let children = []
reg.exec(childrenStr) ? children = childrenStr.trim().split(/(?=\s*<[a-z]+>)\s*/).map(i => formatter(i)) : children.push(childrenStr)
const result = {
tag,
children
}
Object.keys(attrs).length && (result.attrs = attrs)
return result
}
var str = `<ul id="a" class="b c" data-test="test">
<li>111</li>
<li>222</li>
</ul>`
console.log(formatter(str)) // {"tag":"ul","children":[{"tag":"li","children":["111"]},{"tag":"li","children":["222"]}],"attrs":{"id":"a","class":"b c","data-test":"test"}}