Guest User

Untitled

a guest
Sep 20th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. const textNode = (input, cursor, curr)=>{
  2. const idx = input.indexOf('<', cursor);
  3. curr.tag.children.push({
  4. type:'text', text:input.substring(cursor, idx)
  5. });
  6. return idx;
  7. };
  8.  
  9. const attributes = attrStr => {
  10. if(!attrStr) return null;
  11. const attrStack = [], reg = /(\w+-?\w+)(?:=(["'])(.*?)\2)?/g;
  12. let result;
  13. while (result = reg.exec(attrStr)){
  14. attrStack.push({key :result[1], value:result[3] || true});
  15. }
  16. return attrStack;
  17. };
  18.  
  19.  
  20. const elementNode = (input, cursor, idx, curr) => {
  21. let isClose = input[idx -1] === '/';
  22. let innerTagStr = input.substring(cursor + 1, idx - (isClose ? 1 : 0));
  23. const[_, name, attrStr] = innerTagStr.match(/(\S+)\s+(\S+.*)/) || [undefined, innerTagStr, undefined];
  24. const attr = attributes(attrStr);
  25. const tag = {name, type:'node', attr, children:[]};
  26. curr.tag.children.push(tag);
  27. if(!isClose){
  28. return {tag, back:curr};
  29. }
  30. return curr;
  31. };
  32.  
  33. const parser = input => {
  34. input = input.trim();
  35. const result = {name : 'ROOT', type:'node', children: []};
  36.  
  37. let curr = {tag:result}, i = 0, j = input.length;
  38.  
  39. while(i<j){
  40. const cursor = i;
  41. if(input[cursor] === '<'){
  42. const idx = input.indexOf('>', cursor);
  43. i = idx + 1;
  44. if(input[cursor + 1] ==='/'){
  45. curr = curr.back;
  46. }else{
  47.  
  48. curr = elementNode(input, cursor, idx, curr);
  49. }
  50. }else i = textNode(input, cursor, curr);
  51. }
  52.  
  53. return result;
  54. };
  55.  
  56. 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