简体   繁体   中英

How to replace \n new line character in string so that <p> tag can show new line

In a react application I am working on there is a condition that:

when a string has a new line character the

<p>{string}</p> tag in which string is to be displayed should be replaced with HTML new line character.

But of course this does not work.

Things I have already tried but did not work for me:

const string = Hello\\nHii

  1. <p>{string.replace('\\n', <br />)}</p>

output:

Hello<br />Hii

  1. <p>{string.replace('\\n', &amp;)}</p>

output:

Hello Hii

I found the above suggestions in the following answers:

the val of a textarea doesnt take new lines into account

There are two options.

  1. Using pre tag or css property white-space: pre :

    <p><pre>{string}</pre></p>

  2. Using dangerouslySetInnerHTML :

    <p dangerouslySetInnerHTML={{__html: string.replace('\\n', '<br />')}}></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM