JSFiddle - React, Tailwind, and code Playground

by emilcieslar

JavaScript

let finalString = []

const wordSplit = (w, t) => {
  // remove all line breaks
  const newText = t.replace(/(\r\n|\n|\r)/gm, "");
  // if newText is longer than w, add line break
  if (newText.length > w) {
    // find w character and split string ONLY IF it's not in the middle of a word
    let wString = newText.substring(w)
    let newString;
    if (wString.substring(1) !== " ") {
      const firstString = newText.substring(0, w)
      const removeSpaces = firstString.split(" ");
      // get last item in array - this will be the start of the new line
      const lastItem = removeSpaces.slice(-1)[0]
      const otherItems = removeSpaces.slice(0, -1)
      const stringItems = otherItems.join(" ");
      let string = stringItems + "\n"
      debugger
      finalString.push(string)
      newString = newText.replace(stringItems, "")
    }

    // continue with rest of string
    wordSplit(w, newString)
  } else {
    finalString.push(newText)
  }
  finalString.join()
  return finalString.join("")
}

wordSplit(24, "How important is it that your next job has a flexible remote work policy?");