0

I am using the substring method to limit the number of characters on each line. The issue I am facing is that the word breaks when the character limit is reached. I want whole words to be preserved. Are there any functions or logic which can limit by character count without breaking up words?

let MaxCharPerLine = 10;

let Inctext = "Sample text to print 10 charachters each line";

for (let i = 0; i < Inctext.length; i += MaxCharPerLine) {
  console.log(Inctext.substring(i, i + MaxCharPerLine))
}

Output:

Sample tex
t to print
 10 charac
hters each
 line

Output I want:

Sample
text to
print 10
characters
each line 
Andrew
  • 3,825
  • 4
  • 30
  • 44
  • 2
    You expected output has lines that contain more than 10 characters though? Can you describe the logic for when to keep a word on the current line vs when to put it onto a new line? – Nick Parsons Dec 20 '22 at 10:52
  • 1
    You could split at the nearest space to every 10th character, but this wouldn't give you the output you specify (as '10' would be on the second line). Please specify the rules you expect to implement to achieve your output. – Rory McCrossan Dec 20 '22 at 10:57
  • @NickParsons Thanks for your response. For example if you look on the first line of output "Sample tex" is printed but the work "text" also breaks. A condition that should prioritize word and spaces first than characters. So it should only print (first line output) "Sample" in this case. – SalProgrammer Dec 20 '22 at 11:21
  • @RoryMcCrossan thanks for your response. I think it would be perfect if it prioritizes word and spaces than characters. If MaxCharPerLine is 10 than it is supposed to print 10 characters but most importantly if the word breaks, it should only print characters that occur before " " (space). Like if you look the first line it should print only "Sample". – SalProgrammer Dec 20 '22 at 11:28
  • The answer to your titular question: No, you cannot use `substring`. – Bergi Dec 20 '22 at 11:37
  • @bergi thanks for your response. What other logic can I use? – SalProgrammer Dec 20 '22 at 11:38
  • See the duplicates I just dug up – Bergi Dec 20 '22 at 11:41

0 Answers0