Skip to content

New line that is visible in both HTML and console.log

I have this simple JavaScript:

function property() {
    var ua = document.getElementById('greenBack').innerHTML;
    var finals;
    finals = ua;
    if (ua.indexOf('p')) {
        finals += '<br>n Unknown Error';
    } 
    return finals;
}

The problem is that I would like a newline to be shown when the function output is displayed in console.log() without the <br> tag (because <br> displays on the console) , but also be able to write the text “Unknown Error” to a newline in html without using <br>.

Is there any solution to display a newline in HTML and the console without nor <br> ?

Answer

Just use n for the console output. Then, when showing the text on a HTML page, you can either:

  • replace n with <br>
  • or wrap a <pre> tag around it which will respect white-space and newlines
  • or use CSS-style white-space: pre-wrap; on any other HTML element

See this jsFiddle

$('#test').text('Thisn   isn  antest');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="test"></pre>