to-markdown.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. /*
  2. * to-markdown - an HTML to Markdown converter
  3. *
  4. * Copyright 2011, Dom Christie
  5. * Licenced under the MIT licence
  6. *
  7. */
  8. var toMarkdown = function(string) {
  9. var ELEMENTS = [
  10. {
  11. patterns: 'p',
  12. replacement: function(str, attrs, innerHTML) {
  13. return innerHTML ? '\n\n' + innerHTML + '\n' : '';
  14. }
  15. },
  16. {
  17. patterns: 'br',
  18. type: 'void',
  19. replacement: '\n'
  20. },
  21. {
  22. patterns: 'h([1-6])',
  23. replacement: function(str, hLevel, attrs, innerHTML) {
  24. var hPrefix = '';
  25. for(var i = 0; i < hLevel; i++) {
  26. hPrefix += '#';
  27. }
  28. return '\n\n' + hPrefix + ' ' + innerHTML + '\n';
  29. }
  30. },
  31. {
  32. patterns: 'hr',
  33. type: 'void',
  34. replacement: '\n\n* * *\n'
  35. },
  36. {
  37. patterns: 'a',
  38. replacement: function(str, attrs, innerHTML) {
  39. var href = attrs.match(attrRegExp('href')),
  40. title = attrs.match(attrRegExp('title'));
  41. return href ? '[' + innerHTML + ']' + '(' + href[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : str;
  42. }
  43. },
  44. {
  45. patterns: ['b', 'strong'],
  46. replacement: function(str, attrs, innerHTML) {
  47. return innerHTML ? '**' + innerHTML + '**' : '';
  48. }
  49. },
  50. {
  51. patterns: ['i', 'em'],
  52. replacement: function(str, attrs, innerHTML) {
  53. return innerHTML ? '_' + innerHTML + '_' : '';
  54. }
  55. },
  56. {
  57. patterns: 'code',
  58. replacement: function(str, attrs, innerHTML) {
  59. return innerHTML ? '`' + innerHTML + '`' : '';
  60. }
  61. },
  62. {
  63. patterns: 'img',
  64. type: 'void',
  65. replacement: function(str, attrs, innerHTML) {
  66. var src = attrs.match(attrRegExp('src')),
  67. alt = attrs.match(attrRegExp('alt')),
  68. title = attrs.match(attrRegExp('title'));
  69. return '![' + (alt && alt[1] ? alt[1] : '') + ']' + '(' + src[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')';
  70. }
  71. }
  72. ];
  73. for(var i = 0, len = ELEMENTS.length; i < len; i++) {
  74. if(typeof ELEMENTS[i].patterns === 'string') {
  75. string = replaceEls(string, { tag: ELEMENTS[i].patterns, replacement: ELEMENTS[i].replacement, type: ELEMENTS[i].type });
  76. }
  77. else {
  78. for(var j = 0, pLen = ELEMENTS[i].patterns.length; j < pLen; j++) {
  79. string = replaceEls(string, { tag: ELEMENTS[i].patterns[j], replacement: ELEMENTS[i].replacement, type: ELEMENTS[i].type });
  80. }
  81. }
  82. }
  83. function replaceEls(html, elProperties) {
  84. var pattern = elProperties.type === 'void' ? '<' + elProperties.tag + '\\b([^>]*)\\/?>' : '<' + elProperties.tag + '\\b([^>]*)>([\\s\\S]*?)<\\/' + elProperties.tag + '>',
  85. regex = new RegExp(pattern, 'gi'),
  86. markdown = '';
  87. if(typeof elProperties.replacement === 'string') {
  88. markdown = html.replace(regex, elProperties.replacement);
  89. }
  90. else {
  91. markdown = html.replace(regex, function(str, p1, p2, p3) {
  92. return elProperties.replacement.call(this, str, p1, p2, p3);
  93. });
  94. }
  95. return markdown;
  96. }
  97. function attrRegExp(attr) {
  98. return new RegExp(attr + '\\s*=\\s*["\']?([^"\']*)["\']?', 'i');
  99. }
  100. // Pre code blocks
  101. string = string.replace(/<pre\b[^>]*>`([\s\S]*)`<\/pre>/gi, function(str, innerHTML) {
  102. innerHTML = innerHTML.replace(/^\t+/g, ' '); // convert tabs to spaces (you know it makes sense)
  103. innerHTML = innerHTML.replace(/\n/g, '\n ');
  104. return '\n\n ' + innerHTML + '\n';
  105. });
  106. // Lists
  107. // Escape numbers that could trigger an ol
  108. // If there are more than three spaces before the code, it would be in a pre tag
  109. // Make sure we are escaping the period not matching any character
  110. string = string.replace(/^(\s{0,3}\d+)\. /g, '$1\\. ');
  111. // Converts lists that have no child lists (of same type) first, then works it's way up
  112. var noChildrenRegex = /<(ul|ol)\b[^>]*>(?:(?!<ul|<ol)[\s\S])*?<\/\1>/gi;
  113. while(string.match(noChildrenRegex)) {
  114. string = string.replace(noChildrenRegex, function(str) {
  115. return replaceLists(str);
  116. });
  117. }
  118. function replaceLists(html) {
  119. html = html.replace(/<(ul|ol)\b[^>]*>([\s\S]*?)<\/\1>/gi, function(str, listType, innerHTML) {
  120. var lis = innerHTML.split('</li>');
  121. lis.splice(lis.length - 1, 1);
  122. for(i = 0, len = lis.length; i < len; i++) {
  123. if(lis[i]) {
  124. var prefix = (listType === 'ol') ? (i + 1) + ". " : "* ";
  125. lis[i] = lis[i].replace(/\s*<li[^>]*>([\s\S]*)/i, function(str, innerHTML) {
  126. innerHTML = innerHTML.replace(/^\s+/, '');
  127. innerHTML = innerHTML.replace(/\n\n/g, '\n\n ');
  128. // indent nested lists
  129. innerHTML = innerHTML.replace(/\n([ ]*)+(\*|\d+\.) /g, '\n$1 $2 ');
  130. return prefix + innerHTML;
  131. });
  132. }
  133. }
  134. return lis.join('\n');
  135. });
  136. return '\n\n' + html.replace(/[ \t]+\n|\s+$/g, '');
  137. }
  138. // Blockquotes
  139. var deepest = /<blockquote\b[^>]*>((?:(?!<blockquote)[\s\S])*?)<\/blockquote>/gi;
  140. while(string.match(deepest)) {
  141. string = string.replace(deepest, function(str) {
  142. return replaceBlockquotes(str);
  143. });
  144. }
  145. function replaceBlockquotes(html) {
  146. html = html.replace(/<blockquote\b[^>]*>([\s\S]*?)<\/blockquote>/gi, function(str, inner) {
  147. inner = inner.replace(/^\s+|\s+$/g, '');
  148. inner = cleanUp(inner);
  149. inner = inner.replace(/^/gm, '> ');
  150. inner = inner.replace(/^(>([ \t]{2,}>)+)/gm, '> >');
  151. return inner;
  152. });
  153. return html;
  154. }
  155. function cleanUp(string) {
  156. string = string.replace(/^[\t\r\n]+|[\t\r\n]+$/g, ''); // trim leading/trailing whitespace
  157. string = string.replace(/\n\s+\n/g, '\n\n');
  158. string = string.replace(/\n{3,}/g, '\n\n'); // limit consecutive linebreaks to 2
  159. return string;
  160. }
  161. return cleanUp(string);
  162. };
  163. if (typeof exports === 'object') {
  164. exports.toMarkdown = toMarkdown;
  165. }