replace \n with unicode to display new line in html correctly

14,466

You can replace \n with break line <br/> and then add as innerHTML like

let str = 'line first \n     line-second-preceded-with-a-few-spaces';
str = str.replace(/ /g, '\u00a0');
str = str.split("\n").join("<br/>")
document.getElementById("d").innerHTML = str;
<div id="d"></div>

Or you use replace(/\n/g, "<br/>");. This would also do the same

let str = 'line first \n     line-second-preceded-with-a-few-spaces';
str = str.replace(/ /g, '\u00a0').replace(/\n/g, "<br/>");
document.getElementById("d").innerHTML = str;
<div id="d"></div>

Or you can also wrap your string containing \n and " " in pre tag to treat them as new line characters and white spaces

let str = 'line first \n     line-second-preceded-with-a-few-spaces';

document.getElementById("d").innerHTML = `<pre>${str}</pre>`;
<div id="d"></div>

Note : The pre element should be used for text that has typographic formatting that affects the meaning of the content, such as in poems, ASCII art, transcripts, and, of course, computer code

Share:
14,466
Malvinka
Author by

Malvinka

Updated on June 11, 2022

Comments

  • Malvinka
    Malvinka almost 2 years

    I have a multi-line string:

    let str = 'line first \n     line-second-preceded-with-a-few-spaces';
    

    I would like to inject it into HTML code. I managed to replace all spaces with replace(/ /g, '\u00a0') and I would like to do the same with \n but none of the Unicode values mentioned in Wikipedia seem to work.

    The Unicode standard defines a number of characters that conforming applications should recognize as line terminators:

    LF:    Line Feed, U+000A
    VT:    Vertical Tab, U+000B
    FF:    Form Feed, U+000C
    CR:    Carriage Return, U+000D
    CR+LF: CR (U+000D) followed by LF (U+000A)
    NEL:   Next Line, U+0085
    LS:    Line Separator, U+2028
    PS:    Paragraph Separator, U+2029
    
    {str.replace(/ /g, '\u00a0').replace(/(?:\r\n|\r|\n)/g, '\u000a')}
    

    What is the proper way to do that?