htmlparser.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. /**
  2. * author: Di (微信小程序开发工程师)
  3. * organization: WeAppDev(微信小程序开发论坛)(http://weappdev.com)
  4. * 垂直微信小程序开发交流社区
  5. *
  6. * github地址: https://github.com/icindy/wxParse
  7. *
  8. * for: 微信小程序富文本解析
  9. * detail : http://weappdev.com/t/wxparse-alpha0-1-html-markdown/184
  10. */
  11. // Regular Expressions for parsing tags and attributes
  12. var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
  13. var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
  14. var attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; // Empty Elements - HTML 5
  15. var empty = makeMap("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr");
  16. // Block Elements - HTML 5
  17. var block = makeMap("a,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");
  18. // Inline Elements - HTML 5
  19. var inline = makeMap("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");
  20. // Elements that you can, intentionally, leave open
  21. // (and which close themselves)
  22. var closeSelf = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
  23. // Attributes that have their values filled in disabled="disabled"
  24. var fillAttrs = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
  25. // Special Elements (can contain anything)
  26. var special = makeMap("wxxxcode-style,script,style,view,scroll-view,block");
  27. function HTMLParser(html, handler) {
  28. var index;
  29. var chars;
  30. var match;
  31. var stack = [];
  32. var last = html;
  33. stack.last = function () {
  34. return this[this.length - 1];
  35. };
  36. while (html) {
  37. chars = true;
  38. // Make sure we're not in a script or style element
  39. if (!stack.last() || !special[stack.last()]) {
  40. // Comment
  41. if (html.indexOf("<!--") == 0) {
  42. index = html.indexOf("-->");
  43. if (index >= 0) {
  44. if (handler.comment) {
  45. handler.comment(html.substring(4, index));
  46. }
  47. html = html.substring(index + 3);
  48. chars = false;
  49. }
  50. // end tag
  51. } else if (html.indexOf("</") == 0) {
  52. match = html.match(endTag);
  53. if (match) {
  54. html = html.substring(match[0].length);
  55. match[0].replace(endTag, parseEndTag);
  56. chars = false;
  57. }
  58. // start tag
  59. } else if (html.indexOf("<") == 0) {
  60. match = html.match(startTag);
  61. if (match) {
  62. html = html.substring(match[0].length);
  63. match[0].replace(startTag, parseStartTag);
  64. chars = false;
  65. }
  66. }
  67. if (chars) {
  68. index = html.indexOf("<");
  69. var text = index < 0 ? html : html.substring(0, index);
  70. html = index < 0 ? "" : html.substring(index);
  71. if (handler.chars) {
  72. handler.chars(text);
  73. }
  74. }
  75. } else {
  76. html = html.replace(new RegExp("([\\s\\S]*?)<\/" + stack.last() + "[^>]*>"), function (all, text) {
  77. text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, "$1$2");
  78. if (handler.chars) {
  79. handler.chars(text);
  80. }
  81. return "";
  82. });
  83. parseEndTag("", stack.last());
  84. }
  85. if (html == last) {
  86. throw "Parse Error: " + html;
  87. }
  88. last = html;
  89. }
  90. // Clean up any remaining tags
  91. parseEndTag();
  92. function parseStartTag(tag, tagName, rest, unary) {
  93. tagName = tagName.toLowerCase();
  94. if (block[tagName]) {
  95. while (stack.last() && inline[stack.last()]) {
  96. parseEndTag("", stack.last());
  97. }
  98. }
  99. if (closeSelf[tagName] && stack.last() == tagName) {
  100. parseEndTag("", tagName);
  101. }
  102. unary = empty[tagName] || !!unary;
  103. if (!unary) {
  104. stack.push(tagName);
  105. }
  106. if (handler.start) {
  107. var attrs = [];
  108. rest.replace(attr, function (match, name) {
  109. var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : "";
  110. attrs.push({
  111. name: name,
  112. value: value,
  113. escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') //"
  114. });
  115. });
  116. if (handler.start) {
  117. handler.start(tagName, attrs, unary);
  118. }
  119. }
  120. }
  121. function parseEndTag(tag, tagName) {
  122. // If no tag name is provided, clean shop
  123. if (!tagName) {
  124. var pos = 0;
  125. // Find the closest opened tag of the same type
  126. } else {
  127. for (var pos = stack.length - 1; pos >= 0; pos--) {
  128. if (stack[pos] == tagName) {
  129. break;
  130. }
  131. }
  132. }
  133. if (pos >= 0) {
  134. // Close all the open elements, up the stack
  135. for (var i = stack.length - 1; i >= pos; i--) {
  136. if (handler.end) {
  137. handler.end(stack[i]);
  138. }
  139. }
  140. // Remove the open elements from the stack
  141. stack.length = pos;
  142. }
  143. }
  144. }
  145. ;
  146. function makeMap(str) {
  147. var obj = {};
  148. var items = str.split(",");
  149. for (var i = 0; i < items.length; i++) {
  150. obj[items[i]] = true;
  151. }
  152. return obj;
  153. }
  154. module.exports = HTMLParser;