You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

htmlparser.js 4.8 KiB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. /**
  2. *
  3. * htmlParser改造自: https://github.com/blowsie/Pure-JavaScript-HTML5-Parser
  4. *
  5. * author: Di (微信小程序开发工程师)
  6. * organization: WeAppDev(微信小程序开发论坛)(http://weappdev.com)
  7. * 垂直微信小程序开发交流社区
  8. *
  9. * github地址: https://github.com/icindy/wxParse
  10. *
  11. * for: 微信小程序富文本解析
  12. * detail : http://weappdev.com/t/wxparse-alpha0-1-html-markdown/184
  13. */
  14. // Regular Expressions for parsing tags and attributes
  15. const startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z0-9_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
  16. const endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
  17. const attr = /([a-zA-Z0-9_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g;
  18. function makeMap(str) {
  19. const obj = {};
  20. const items = str.split(',');
  21. for (let i = 0; i < items.length; i += 1) obj[items[i]] = true;
  22. return obj;
  23. }
  24. // Empty Elements - HTML 5
  25. const empty = makeMap('area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr');
  26. // Block Elements - HTML 5
  27. const block = makeMap('address,code,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video');
  28. // Inline Elements - HTML 5
  29. const inline = makeMap('a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var');
  30. // Elements that you can, intentionally, leave open
  31. // (and which close themselves)
  32. const closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr');
  33. // Attributes that have their values filled in disabled="disabled"
  34. const fillAttrs = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected');
  35. function HTMLParser(html, handler) {
  36. let index;
  37. let chars;
  38. let match;
  39. let last = html;
  40. const stack = [];
  41. stack.last = () => stack[stack.length - 1];
  42. function parseEndTag(tag, tagName) {
  43. // If no tag name is provided, clean shop
  44. let pos;
  45. if (!tagName) {
  46. pos = 0;
  47. } else {
  48. // Find the closest opened tag of the same type
  49. tagName = tagName.toLowerCase();
  50. for (pos = stack.length - 1; pos >= 0; pos -= 1) {
  51. if (stack[pos] === tagName) break;
  52. }
  53. }
  54. if (pos >= 0) {
  55. // Close all the open elements, up the stack
  56. for (let i = stack.length - 1; i >= pos; i -= 1) {
  57. if (handler.end) handler.end(stack[i]);
  58. }
  59. // Remove the open elements from the stack
  60. stack.length = pos;
  61. }
  62. }
  63. function parseStartTag(tag, tagName, rest, unary) {
  64. tagName = tagName.toLowerCase();
  65. if (block[tagName]) {
  66. while (stack.last() && inline[stack.last()]) {
  67. parseEndTag('', stack.last());
  68. }
  69. }
  70. if (closeSelf[tagName] && stack.last() === tagName) {
  71. parseEndTag('', tagName);
  72. }
  73. unary = empty[tagName] || !!unary;
  74. if (!unary) stack.push(tagName);
  75. if (handler.start) {
  76. const attrs = [];
  77. rest.replace(attr, function genAttr(matches, name) {
  78. const value = arguments[2] || arguments[3] || arguments[4] || (fillAttrs[name] ? name : '');
  79. attrs.push({
  80. name,
  81. value,
  82. escaped: value.replace(/(^|[^\\])"/g, '$1\\"'), // "
  83. });
  84. });
  85. if (handler.start) {
  86. handler.start(tagName, attrs, unary);
  87. }
  88. }
  89. }
  90. while (html) {
  91. chars = true;
  92. if (html.indexOf('</') === 0) {
  93. match = html.match(endTag);
  94. if (match) {
  95. html = html.substring(match[0].length);
  96. match[0].replace(endTag, parseEndTag);
  97. chars = false;
  98. }
  99. // start tag
  100. } else if (html.indexOf('<') === 0) {
  101. match = html.match(startTag);
  102. if (match) {
  103. html = html.substring(match[0].length);
  104. match[0].replace(startTag, parseStartTag);
  105. chars = false;
  106. }
  107. }
  108. if (chars) {
  109. index = html.indexOf('<');
  110. let text = '';
  111. while (index === 0) {
  112. text += '<';
  113. html = html.substring(1);
  114. index = html.indexOf('<');
  115. }
  116. text += index < 0 ? html : html.substring(0, index);
  117. html = index < 0 ? '' : html.substring(index);
  118. if (handler.chars) handler.chars(text);
  119. }
  120. if (html === last) throw new Error(`Parse Error: ${html}`);
  121. last = html;
  122. }
  123. // Clean up any remaining tags
  124. parseEndTag();
  125. }
  126. export default HTMLParser;