Created
January 24, 2018 08:42
-
-
Save breakstorm/cf98a191f7f380e522c741ca87d20004 to your computer and use it in GitHub Desktop.
Revisions
-
breakstorm created this gist
Jan 24, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,46 @@ const textNode = (text, targetNode)=>{ if(text.length) targetNode.push({tag:{type:"TEXT", text}}); return ''; } const htmlparser = (input) => { const stacks = [], result = {tag:{TYPE:"ROOT", children: []}}; let cursor = 0, stack = result; let char = '', text=''; // debugger; while(input.length > cursor) { char = input[cursor++]; if(char === '<') { text = textNode(text, stack.tag.children); if( input[cursor++] !== '/' ) { let element = input.substring(cursor-1, cursor = input.indexOf('>', cursor)) // <____ /> 형태 조건 // if(element.indexOf('/') !== -1) element = element.substring(0, element.indexOf('/')) const isClose = input[cursor] === '/'; if(isClose) name = name.substr(0, name.length -1); stack.tag.children.push({tag:{TYPE:"NODE", element, children: []}}) cursor++; }else { // </ ___> 형태 조건 cursor = input.indexOf('>', cursor)+1; } }else { text += char; } } console.log(stack) } const str = `<img/> <div> a <a>b</a> c <img/> d </div>` htmlparser(str);