Split Long Paragraphs

Splits long paragraphs at the period nearest to the split point.

  1. // ==UserScript==
  2. // @name Split Long Paragraphs
  3. // @namespace http://tampermonkey.net/
  4. // @version 2
  5. // @description Splits long paragraphs at the period nearest to the split point.
  6. // @match *://ranobes.top/*
  7. // @icon https://www.google.com/s2/favicons?sz=64&domain=ranobes.top
  8. // @license MIT
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. function ellipsize(s) {
  16. return s.substring(0, 64).trim().replace(/[^\w\s\d]+$/, "") + "...";
  17. }
  18.  
  19. function log(text) {
  20. console.log(`Split Long Paragraphs: ${text}`);
  21. }
  22.  
  23. const MAX_WORD_COUNT = 80;
  24. const section = document.querySelector(".story #arrticle");
  25.  
  26. if (!section) {
  27. return;
  28. }
  29.  
  30. const nodes = Array.from(section.querySelectorAll('p'));
  31.  
  32. section.childNodes.forEach(child => {
  33. if (child.nodeType === Node.TEXT_NODE) {
  34. nodes.push(child);
  35. }
  36. })
  37.  
  38. for (let i = 0; i < nodes.length; i++) {
  39. const node = nodes[i];
  40. const text = node.textContent.trim();
  41. const words = text.split(/\s+/);
  42.  
  43. // Max word count before splitting
  44. if (words.length > MAX_WORD_COUNT + Math.floor(MAX_WORD_COUNT / 2)) {
  45. // Find closest split point to MAX_WORD_COUNT at a period
  46. const sentences = text.split(/(?<=[^\.]\.)\s+/);
  47. let sentenceIndex = 0;
  48. let wordCount = 0;
  49.  
  50. for (const sentence of sentences) {
  51. wordCount += sentence.split(/\s+/).length;
  52. // log(`${ellipsize(sentence)} totalWordCount:${wordCount}`);
  53.  
  54. if (wordCount >= MAX_WORD_COUNT) {
  55. break;
  56. }
  57.  
  58. sentenceIndex += 1;
  59. }
  60.  
  61. if (wordCount !== 0) {
  62. log(`Splitting... \`${ellipsize(text)}\` wordCount:${words.length} sentenceIndex:${sentenceIndex} totalSentences:${sentences.length}`);
  63.  
  64. node.textContent = '';
  65.  
  66. let p = document.createElement('p');
  67. p.textContent = sentences.slice(0, sentenceIndex + 1).join(" ").trim();
  68. node.parentNode.insertBefore(p, node);
  69.  
  70. p = document.createElement('p');
  71. p.textContent = sentences.slice(sentenceIndex + 1).join(" ").trim();
  72. node.parentNode.insertBefore(p, node);
  73.  
  74. nodes.push(p);
  75. node.remove();
  76. }
  77. }
  78. }
  79. })();