Search code examples
javascriptarraysstringline-breaks

Javascript - Adding line breaks to array strings


I have a script that displays a random sentence on button click. I would like to add a line break to some of the sentences. Example:

"This is the first sentence"

becomes:

"This is
the first sentence"

I have tried using \n and <br>, but none works.
What else could I try?

    const p = document.getElementById("sentences");
    const origSentences = ["This is the first sentence.", "This is the second sentence.", "This is the third sentence."];
    let remainingSentences = [];

    function randomSentence() {
        if (remainingSentences.length === 0) remainingSentences = origSentences.slice();
        const {
            length
        } = remainingSentences;
        const [quote] = remainingSentences.splice(Math.floor(Math.random() * length), 1);
        p.textContent = quote;
    }
<p><button onclick="randomSentence()" type="button">Random Sentence</button></p>
<p id="sentences"></p>


Solution

  • If you assign your quote to the textContent field of your paragraph p, it will be rendered as plain text. If you instead use innerHTML, it will parse and render any HTML you provide.

    See example.

    const p = document.getElementById("sentences");
    const origSentences = [
      "This is the <br /> first sentence.",
      "This is the second sentence.",
      "This is the <br /> third sentence."
    ];
    let remainingSentences = [];
    
    function randomSentence() {
      if (remainingSentences.length === 0)
        remainingSentences = origSentences.slice();
      const { length } = remainingSentences;
      const [quote] = remainingSentences.splice(
        Math.floor(Math.random() * length),
        1
      );
      p.innerHTML = quote;
    }
    <p>
      <button 
        onclick="randomSentence()" 
        type="button">
        Random Sentence
      </button>
    </p>
    
    <p id="sentences"></p>