JSFiddle - React, Tailwind, and code Playground

by emilcieslar

JavaScript

function sentence(w, text) {
  let textArr = text.split(' ')

  let total = []
  let index = 0;
  while (true) {
    let localLength = 0;
    let val = '';

    for (let i = 0; i < textArr.length; i++) {
      localLength = localLength + textArr[i].length

      if (localLength <= w) {

        val = val + ' ' + textArr[i]

      } else {
        index = i - 1

        break;
      }
    }

    total.push(val)
    console.log(total)
    textArr = textArr.slice(index + 1, textArr.length)

    if (textArr.length === 0) {
      break;
    }

  }

  for (let j = 0; j < total.length; j++) {
    console.log(total[j])
  }
}

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