{"action":"opened","issue":{"url":"https://api.github.com/repos/kaola-fed/blog/issues/48","repository_url":"https://api.github.com/repos/kaola-fed/blog","labels_url":"https://api.github.com/repos/kaola-fed/blog/issues/48/labels{/name}","comments_url":"https://api.github.com/repos/kaola-fed/blog/issues/48/comments","events_url":"https://api.github.com/repos/kaola-fed/blog/issues/48/events","html_url":"https://github.com/kaola-fed/blog/issues/48","id":230695360,"number":48,"title":"实现一个简单的html ast解析算法","user":{"login":"jerryni","id":7235595,"avatar_url":"https://avatars0.githubusercontent.com/u/7235595?v=3","gravatar_id":"","url":"https://api.github.com/users/jerryni","html_url":"https://github.com/jerryni","followers_url":"https://api.github.com/users/jerryni/followers","following_url":"https://api.github.com/users/jerryni/following{/other_user}","gists_url":"https://api.github.com/users/jerryni/gists{/gist_id}","starred_url":"https://api.github.com/users/jerryni/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/jerryni/subscriptions","organizations_url":"https://api.github.com/users/jerryni/orgs","repos_url":"https://api.github.com/users/jerryni/repos","events_url":"https://api.github.com/users/jerryni/events{/privacy}","received_events_url":"https://api.github.com/users/jerryni/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"assignees":[],"milestone":null,"comments":0,"created_at":"2017-05-23T12:50:25Z","updated_at":"2017-05-23T12:50:25Z","closed_at":null,"body":"---\r\ntitle: 实现一个简单的html ast解析算法\r\ndate: 2017-05-23\r\n---\r\n\r\n<!-- 为了更方便归档，请先完善以上信息，正文贴下面 -->\r\n<!--\r\n注意点：\r\n0. 文章中的资源（主要是图片）引用请使用 HTTPS\r\n1. 文章末可以加上自己的署名，如： by [Kaola](http://www.kaola.com)\r\n2. 最好不要用 NOS 图床，感觉加防盗链是迟早的事\r\n-->\r\n\r\n## 概述\r\n\r\nhtml ast解析算法的过程是将一段html字符串，解析成一个javascript对象。\r\n\r\n## 示例字符串\r\n\r\n```html\r\n<div>\r\n    <input r-value=\"{name}\" />\r\n    <p>\r\n        <span></span>\r\n        <span style=\"display:block;\">\r\n            描述信息2\r\n            <span>{name}</span>\r\n        </span>\r\n    </p>\r\n</div>\r\n```\r\n\r\n## 思路分析\r\n\r\n整体实现分析：\r\n \r\n1. 通过正则匹配出token，设置node，添加到ast对象中，同时截取掉剩余的字段\r\n2. 主要的token: 开标签`<div>`,`<p>`等，自闭合标签`<input />`，闭合标签`</div>`, `</p>`等\r\n3. 实现范围可以先从标签名开始，再添加属性，再解析文本(textNode)\r\n\r\n代码思路：\r\n\r\n1. 用一个数组储存树结构，children表示分支\r\n2. 先匹配到一个`div`开标签，push进数组\r\n3. 匹配到input自闭合标签放入div.children\r\n4. 匹配到p标签放入div.children\r\n5. 匹配到span放入p.children\r\n6. 匹配到`</span>`结束标签，表示后面的标签需要加入到p.children而不是span.children\r\n7. 递归到没有开标签为止\r\n\r\n## 代码实现\r\n\r\n分布解析的动态demo，代码每一步都有详细的解释:\r\n\r\n[online demo](https://jerryni.github.io/algorithom/demos/html.ast.parser.html)\r\n\r\n[github源码](https://github.com/jerryni/algorithom/blob/master/demos/html.ast.parser.html)\r\n\r\nby [Kaola nrz](https://github.com/jerryni)"}}
{"actor":{"display_login":"jerryni"}}