htmlparser.js 5.0 KB

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