extract.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const slug = require('slug');
  2. function makeSlug(title) {
  3. return slug(title, {lower: true});
  4. }
  5. function extractTitleAndPath(markdown) {
  6. const titleRegex = /^#\s(.*)/mi;
  7. let title;
  8. try {
  9. [, title] = markdown.match(titleRegex);
  10. } catch(e) {
  11. throw new Error('Could not find h1 title');
  12. }
  13. const path = `/${makeSlug(title)}`;
  14. return { title, path };
  15. }
  16. function findNextSubtitleIndex(lines) {
  17. const subtitleRegex = /^##\s(.*)/i;
  18. for (let i = 0; i < lines.length; i++) {
  19. const line = lines[i];
  20. const matches = line.match(subtitleRegex);
  21. if (matches) {
  22. return i;
  23. }
  24. }
  25. return -1;
  26. }
  27. function getSection(lines, start, end) {
  28. return lines.slice(start, end).join('\n');
  29. }
  30. function extractSections(markdown) {
  31. let lines = markdown.split('\n');
  32. const subtitleRegex = /^##\s.*/gm;
  33. const contents = markdown.split(/^##\s.*/gm)
  34. .map(c => {
  35. let start = 0;
  36. while(c[start] === '\n') {
  37. start++;
  38. }
  39. let end = c.length - 1;
  40. while(c[end] === '\n') {
  41. end--;
  42. }
  43. return c.substring(start, end + 1);
  44. });
  45. contents.shift();
  46. const titles = lines.filter(l => /^##\s.*/.test(l))
  47. .map(l => l.substr(3));
  48. return titles.map((title, i) => ({
  49. title,
  50. path: `/${makeSlug(title)}`,
  51. content: contents[i]
  52. }));
  53. }
  54. function extract(markdown) {
  55. const { title, path } = extractTitleAndPath(markdown);
  56. const items = extractSections(markdown);
  57. return { title, path, items };
  58. }
  59. module.exports = extract;