How am i able to put new line after n amount of words (characters more specifically, then rounded to words) on javascript?

Viewed 38

I was able to use .replace(/.{40}/g, '$&\n') to put a new line on every 40th character of a word from the input, but that cuts words in the middle. What is a wise choice in the situlation? Thanks!

1 Answers

I don't know the answer. That said, I'd hazard the following system might work:

  • see if the character 41 is equal to [a-zA-Z]
  • if it is indeed the middle of the word, insert a linebreak in the previous whitespace

Hope this might help!

Related