JSFiddle - React, Tailwind, and code Playground

by emilcieslar

JavaScript

function splitMyText(text, w) {
  var cleanedText = text.replace('\n', ' ');

  function findSpace(lastFound = -1, splitText = ``, k = 2) {
    var subString = cleanedText.substring(0, lastFound + w + k);
    var found = subString.lastIndexOf(' ');

    if (subString.replace('\n', '').length >= cleanedText.length) {
      var splitString = subString.substring(lastFound + 1, lastFound + w + k);
      return splitText + splitString;
    }

    if (found === lastFound) {
      return findSpace(found, splitText, k + 1);
    }

    if (found > -1) {
      var splitString = subString.substring(lastFound + 1, found);
      return findSpace(found, splitText + splitString + '\n', 2)
    }
  }

  return findSpace();
}

console.log(splitMyText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.", 25));