筆試題: 實現(xiàn)一個js 解析器 將以下的文本解析為 json對象數(shù)據(jù)

 // 題目 實現(xiàn)一個js 解析器 將以下的文本解析為 json對象數(shù)據(jù)
  const html = `view{
                  heading{}
                  text{}
                }`
// 結(jié)果
  const json ={
    'tagName':'view',
    'children':[
      {
        'tagName':'heading',
        'children':[]
      },
      {
        'tagName':'text',
        'children':[]
      }
    ]
  }

答案: 來自某個大佬提供的思路

function parseHTML(html) {
    const res = []
    parseHTMLTree(html, res)
    console.log(JSON.stringify(res, null, 2))
    return res
  }

  function parseHTMLTree(html, arr) {
    const reg = /\s*([A-Za-z][^{\s]*)\s*{/;
    let match = reg.exec(html)
    while (match) {
      const prev = match[0];
      const tagName = match[1];
      const startIndex = match.index;
      const endIndex = findNextCompare(html, startIndex)
      const tag = {
        tagName,
        children: []
      }

      arr.push(tag)
      const startItem = html.slice(prev.length + startIndex, endIndex)
      parseHTMLTree(startItem, tag.children)
      html = html.slice(endIndex + 1)
      match = reg.exec(html)
    }
  }

  function findNextCompare(str, startIndex, left = '{', right = '}') {
    let stack = [];
    for (let i = startIndex; i < str.length; i++) {
      if (str[i] === left) {
        stack.push(1)
      } else if (str[i] === right) {
        stack.pop()
        if (!stack.length) {
          return i
        }
      }
    }
  }


// 直接運行
parseHTML(html)

// 結(jié)果
[
  {
    "tagName": "view",
    "children": [
      {
        "tagName": "heading",
        "children": []
      },
      {
        "tagName": "text",
        "children": []
      }
    ]
  }
]
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容