Skip to content

Instantly share code, notes, and snippets.

@breakstorm
Created January 24, 2018 08:42
Show Gist options
  • Save breakstorm/cf98a191f7f380e522c741ca87d20004 to your computer and use it in GitHub Desktop.
Save breakstorm/cf98a191f7f380e522c741ca87d20004 to your computer and use it in GitHub Desktop.
htmlparser
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment