JSFiddle - React, Tailwind, and code Playground

by emilcieslar

JavaScript

function getText(str, w) {
  let lineArray = str.split("\n");
  let result = [];
  for (line of lineArray) {
    let wordArray = line.split(" ");
    let length = 0, temp = [];
    for (let i = 0; i < wordArray.length; i++) {
      length += wordArray[i].length;
      if (length > w) break;
      temp.push(wordArray[i]);
      length += 1;
    }
    result.push(temp.join(" "));
  }
  return result.join("\n");
}

console.log(getText("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));