Splitting a text into separate words while maintaining linebreaks

Hi

I have a string of text that contains linebreaks (\n). I want to make one word at a time appear every time I press the mouse. I can do that, however, I have an issue maintaining the linebreaks as they seem to get lost when I split the string. How might I do that?

Here is the sketch.js code

let writtenText = "Lorem ipsum. \ndolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
let myWords = [];
let wordIndex = 0;

let displayText = "";

function setup() {
  createCanvas(400, 400);
  myWords = trim(writtenText.split(" "));
}

function draw() {
  background(220);
}

function mousePressed() {
  document.getElementById("poem").innerHTML+=myWords[wordIndex] + " ";
  wordIndex++;
  if (wordIndex > myWords.length - 1) wordIndex = 0; 
}

And here is a link to the sketch:
https://editor.p5js.org/AndreasRef/sketches/KzmoLzlbT

Can you not split using the linebreaks first "/n" ? This will mean producing an array of strings, then you split each line for spaces.

3 Likes

Your first problem is that you are calling the trim() function on your array of strings. The trim() function is going to remove all leading and trailing whitespace, including newlines, from each word. The second issue is that you’re appending the words as HTML content. In HTML newlines are, by default, treated as just a space. You have two options for including newlines in HTML: 1) set the white-space style property of the container element to the value pre, or 2) replace newlines with <br />.

1 Like