Skip to content

Instantly share code, notes, and snippets.

@breakstorm
Created January 24, 2018 08:42
Show Gist options
  • Select an option

  • Save breakstorm/cf98a191f7f380e522c741ca87d20004 to your computer and use it in GitHub Desktop.

Select an option

Save breakstorm/cf98a191f7f380e522c741ca87d20004 to your computer and use it in GitHub Desktop.

Revisions

  1. breakstorm created this gist Jan 24, 2018.
    46 changes: 46 additions & 0 deletions htmlparser.js
    Original 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);