spaasteam / spaas-daily-practice

spaas团队的每日一练,欢迎小伙伴们提交踊跃答案!
4 stars 2 forks source link

第 56 题: 写一个函数,用js对象来描述html字符串 #69

Open linrunzheng opened 5 years ago

linrunzheng commented 5 years ago

var str = '<ul id="a" class="b c" data-test="test">
  <li>111</li>
  <li>222</li>
</ul>'

function formatter(){

}

->

{
  tag:'ul',
  attrs:{
    id:'a',
    class:"b c",
    'data-test':"test"
  },
  children:[
    {
      tag:'li',
      children:['111']
    },
    {
      tag:'li',
      children:['222']
    }
  ]
}
Htongbing commented 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"}}