extract_desc.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. function extract_desc(text = '', fragment = '') {
  2. var sectionIndex = text.indexOf('\ufffd\ufffd');
  3. var extract = ( sectionIndex !== -1 ? text.substring(0, sectionIndex) : text ).trim().escapeFormatting();
  4. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  5. var section = null;
  6. var regex = /\ufffd{2}(\d)\ufffd{2}([^\n]+)/g;
  7. var sectionHeader = '';
  8. var sectionText = '';
  9. while ( fragment && ( section = regex.exec(text) ) !== null ) {
  10. if ( section[2].replace( / /g, '_' ) !== fragment.replace( / /g, '_' ) ) continue;
  11. sectionHeader = section[2].escapeFormatting();
  12. if ( sectionHeader.length > 240 ) sectionHeader = sectionHeader.substring(0, 240) + '\u2026';
  13. sectionHeader = section_formatting(sectionHeader, section[1]);
  14. sectionText = text.substring(regex.lastIndex);
  15. switch ( section[1] ) {
  16. case '6':
  17. sectionIndex = sectionText.indexOf('\ufffd\ufffd6\ufffd\ufffd');
  18. if ( sectionIndex !== -1 ) sectionText = sectionText.substring(0, sectionIndex);
  19. case '5':
  20. sectionIndex = sectionText.indexOf('\ufffd\ufffd5\ufffd\ufffd');
  21. if ( sectionIndex !== -1 ) sectionText = sectionText.substring(0, sectionIndex);
  22. case '4':
  23. sectionIndex = sectionText.indexOf('\ufffd\ufffd4\ufffd\ufffd');
  24. if ( sectionIndex !== -1 ) sectionText = sectionText.substring(0, sectionIndex);
  25. case '3':
  26. sectionIndex = sectionText.indexOf('\ufffd\ufffd3\ufffd\ufffd');
  27. if ( sectionIndex !== -1 ) sectionText = sectionText.substring(0, sectionIndex);
  28. case '2':
  29. sectionIndex = sectionText.indexOf('\ufffd\ufffd2\ufffd\ufffd');
  30. if ( sectionIndex !== -1 ) sectionText = sectionText.substring(0, sectionIndex);
  31. case '1':
  32. sectionIndex = sectionText.indexOf('\ufffd\ufffd1\ufffd\ufffd');
  33. if ( sectionIndex !== -1 ) sectionText = sectionText.substring(0, sectionIndex);
  34. }
  35. sectionText = sectionText.trim().escapeFormatting().replace( /\ufffd{2}(\d)\ufffd{2}([^\n]+)/g, (match, n, sectionTitle) => {
  36. return section_formatting(sectionTitle, n);
  37. } );
  38. if ( sectionText.length > 1000 ) sectionText = sectionText.substring(0, 1000) + '\u2026';
  39. break;
  40. }
  41. return [extract, sectionHeader, sectionText];
  42. }
  43. function section_formatting(title, n) {
  44. switch ( n ) {
  45. case '1':
  46. title = '***__' + title + '__***';
  47. break;
  48. case '2':
  49. title = '**__' + title + '__**';
  50. break;
  51. case '3':
  52. title = '**' + title + '**';
  53. break;
  54. case '4':
  55. title = '__' + title + '__';
  56. break;
  57. case '5':
  58. title = '*' + title + '*';
  59. break;
  60. }
  61. return title;
  62. }
  63. module.exports = extract_desc;