Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const textNode = (input, cursor, curr)=>{
- const idx = input.indexOf('<', cursor);
- curr.tag.children.push({
- type:'text', text:input.substring(cursor, idx)
- });
- return idx;
- };
- const attributes = attrStr => {
- if(!attrStr) return null;
- const attrStack = [], reg = /(\w+-?\w+)(?:=(["'])(.*?)\2)?/g;
- let result;
- while (result = reg.exec(attrStr)){
- attrStack.push({key :result[1], value:result[3] || true});
- }
- return attrStack;
- };
- const elementNode = (input, cursor, idx, curr) => {
- let isClose = input[idx -1] === '/';
- let innerTagStr = input.substring(cursor + 1, idx - (isClose ? 1 : 0));
- const[_, name, attrStr] = innerTagStr.match(/(\S+)\s+(\S+.*)/) || [undefined, innerTagStr, undefined];
- const attr = attributes(attrStr);
- const tag = {name, type:'node', attr, children:[]};
- curr.tag.children.push(tag);
- if(!isClose){
- return {tag, back:curr};
- }
- return curr;
- };
- const parser = input => {
- input = input.trim();
- const result = {name : 'ROOT', type:'node', children: []};
- let curr = {tag:result}, i = 0, j = input.length;
- while(i<j){
- const cursor = i;
- if(input[cursor] === '<'){
- const idx = input.indexOf('>', cursor);
- i = idx + 1;
- if(input[cursor + 1] ==='/'){
- curr = curr.back;
- }else{
- curr = elementNode(input, cursor, idx, curr);
- }
- }else i = textNode(input, cursor, curr);
- }
- return result;
- };
- console.log('---------', parser('<div style="width:100%">a<a href="#">b</a>c<img alt="이런그림"/>d</div>'));
Add Comment
Please, Sign In to add comment