Replacing newline character in javascript

后端 未结 4 1717
生来不讨喜
生来不讨喜 2021-02-07 02:46

I am trying to replaces instances of \\r or \\n characters in my json object with
for display on a website.

I tried:<

相关标签:
4条回答
  • 2021-02-07 03:24

    Try this:

    myString = myString.replace(/[\r\n]/g, "<br />");
    

    Update: As told by Pointy on the comment below, this would replace a squence of \r\n with two <br />, the correct regex should be:

    myString = myString.replace(/\r?\n/g, "<br />");
    
    0 讨论(0)
  • 2021-02-07 03:25

    This worked for me:

    str = str.replace(/\\n|\\r\\n|\\r/g, '<br/>');
    

    Using double slash

    0 讨论(0)
  • 2021-02-07 03:28

    CSS:

     white-space: pre-wrap;
    

    Is a far more eficient method.

    0 讨论(0)
  • 2021-02-07 03:40

    try replace(/\r\n|\n/, '<br />')

    0 讨论(0)
提交回复
热议问题