htmlparser.js 5.5 KB

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