htmlparser.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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 =
  16. /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z0-9_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
  17. const endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
  18. const attr =
  19. /([a-zA-Z0-9_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g;
  20. function makeMap(str) {
  21. const obj = {};
  22. const items = str.split(",");
  23. for (let i = 0; i < items.length; i += 1) obj[items[i]] = true;
  24. return obj;
  25. }
  26. // Empty Elements - HTML 5
  27. const empty = makeMap(
  28. "area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr",
  29. );
  30. // Block Elements - HTML 5
  31. const block = makeMap(
  32. "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",
  33. );
  34. // Inline Elements - HTML 5
  35. const inline = makeMap(
  36. "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",
  37. );
  38. // Elements that you can, intentionally, leave open
  39. // (and which close themselves)
  40. const closeSelf = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
  41. // Attributes that have their values filled in disabled="disabled"
  42. const fillAttrs = makeMap(
  43. "checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected",
  44. );
  45. function HTMLParser(html, handler) {
  46. let index;
  47. let chars;
  48. let match;
  49. let last = html;
  50. const stack = [];
  51. stack.last = () => stack[stack.length - 1];
  52. function parseEndTag(tag, tagName) {
  53. // If no tag name is provided, clean shop
  54. let pos;
  55. if (!tagName) {
  56. pos = 0;
  57. } else {
  58. // Find the closest opened tag of the same type
  59. tagName = tagName.toLowerCase();
  60. for (pos = stack.length - 1; pos >= 0; pos -= 1) {
  61. if (stack[pos] === tagName) break;
  62. }
  63. }
  64. if (pos >= 0) {
  65. // Close all the open elements, up the stack
  66. for (let i = stack.length - 1; i >= pos; i -= 1) {
  67. if (handler.end) handler.end(stack[i]);
  68. }
  69. // Remove the open elements from the stack
  70. stack.length = pos;
  71. }
  72. }
  73. function parseStartTag(tag, tagName, rest, unary) {
  74. tagName = tagName.toLowerCase();
  75. if (block[tagName]) {
  76. while (stack.last() && inline[stack.last()]) {
  77. parseEndTag("", stack.last());
  78. }
  79. }
  80. if (closeSelf[tagName] && stack.last() === tagName) {
  81. parseEndTag("", tagName);
  82. }
  83. unary = empty[tagName] || !!unary;
  84. if (!unary) stack.push(tagName);
  85. if (handler.start) {
  86. const attrs = [];
  87. rest.replace(attr, function genAttr(matches, name) {
  88. const value =
  89. arguments[2] ||
  90. arguments[3] ||
  91. arguments[4] ||
  92. (fillAttrs[name] ? name : "");
  93. attrs.push({
  94. name,
  95. value,
  96. escaped: value.replace(/(^|[^\\])"/g, '$1\\"'), // "
  97. });
  98. });
  99. if (handler.start) {
  100. handler.start(tagName, attrs, unary);
  101. }
  102. }
  103. }
  104. while (html) {
  105. chars = true;
  106. if (html.indexOf("</") === 0) {
  107. match = html.match(endTag);
  108. if (match) {
  109. html = html.substring(match[0].length);
  110. match[0].replace(endTag, parseEndTag);
  111. chars = false;
  112. }
  113. // start tag
  114. } else if (html.indexOf("<") === 0) {
  115. match = html.match(startTag);
  116. if (match) {
  117. html = html.substring(match[0].length);
  118. match[0].replace(startTag, parseStartTag);
  119. chars = false;
  120. }
  121. }
  122. if (chars) {
  123. index = html.indexOf("<");
  124. let text = "";
  125. while (index === 0) {
  126. text += "<";
  127. html = html.substring(1);
  128. index = html.indexOf("<");
  129. }
  130. text += index < 0 ? html : html.substring(0, index);
  131. html = index < 0 ? "" : html.substring(index);
  132. if (handler.chars) handler.chars(text);
  133. }
  134. if (html === last) throw new Error(`Parse Error: ${html}`);
  135. last = html;
  136. }
  137. // Clean up any remaining tags
  138. parseEndTag();
  139. }
  140. export default HTMLParser;