JSFiddle - React, Tailwind, and code Playground

by emilcieslar

JavaScript

function countNextWord (start, originalText) {
  for (var i = start; i < originalText.length; i++) {
    if (originalText[i] == ' ' || originalText[i] == '\t' ||
      originalText[i] == '\n') {
      return i - start;
    }
  }
  return originalText.length - start - 1;
}

function clearWhiteSpaces (index, originalText) {
  while (originalText[index] == ' ' || originalText[index] == '\t' ||
    originalText[index] == '\n')
    index++;
  return index;
}

function splitText (w, originalText) {
  var nextWord = 0;
  var newText = '';
  w = parseInt (w);
  while (nextWord < originalText.length) {
    var line = '';
    while (line.length < w && nextWord < originalText.length) {
      var wordSize = countNextWord (nextWord, originalText);
      var word = originalText.substring (nextWord, nextWord + wordSize + 1);

      if (wordSize + line.length > w) {

        break;
      }
      nextWord += wordSize + 1;
      line += word;
      nextWord = clearWhiteSpaces (nextWord, originalText);

    }
    line += '\n';
    newText += line;

  }
  return newText === '' ? originalText : newText;

}

console.log (splitText (25, "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.")); // output:
// He ll o
// world