search

Home  >  Q&A  >  body text

javascript - How to output the newline character in a string in html

I obtain a string in the background and output it to the <p> tag in the foreground, but there is a newline character 'n' in the string, and I want to output the newline effect in the same way. How should I deal with this string? I replaced 'n' with <br/> but it still didn't work, and it was output as is.
thank you all

为情所困为情所困2753 days ago1129

reply all(6)I'll reply

  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-14 10:53:21

    There are two ways, one is to set white-space: pre;, the white space will be retained by the browser. Or use

    <pre>
        我是换行字
    
        符串
    </pre>
    

    , the pre element can define pre-formatted text. Text enclosed in a pre element usually preserves whitespace and newlines.

    reply
    0
  • 欧阳克

    欧阳克2017-06-14 10:53:21

    Isn’t the

    line break character n?

    If you are in this situation, change it to </p><p>

    reply
    0
  • 阿神

    阿神2017-06-14 10:53:21

    According to your description, you should need the pre tag.

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-14 10:53:21

    In js, you can use . innerHTML = 'It<br />works' to output html; if it is jQuery, use $.fn.html('It<br />works')!
    ==== I thought it was PHP output
    Use the htmlentities function to output the replaced content!

    reply
    0
  • 阿神

    阿神2017-06-14 10:53:21

    This is possible. It’s best for the questioner to post the code to know the reason

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-06-14 10:53:21

    nvalid in pre

    pre.innerHTML = 'hey,\nman'
    // hey,
    // man

    can be passed in p via replace

    let str = 'hey,\nman'
    str = str.replace(/\n/, '<br>')
    p.innerHTML = str
    // hey,
    // man

    reply
    0
  • Cancelreply