how do i make a js string have newlines instead of showing n?

Unless you are rendering the string as HTML, the line-feeds will be preserved and should not be rendered.

If you are setting the HTML content of an element, you must convert them to line-breaks, unless you specify white-space: pre.

const ref = sel => document.querySelector(sel); // Convenience function

const str = 'I\nLove\nJS!';

ref('.test-textarea-value').value = str;
ref('.test-html-pre').textContent = str;
ref('.test-html-split').innerHTML = str.split('\n').join('<br>');
ref('.test-html-replace').innerHTML = str.replace(/\n/g, '<br>');

.test-html-pre { white-space: pre; }
<textarea rows="3" class="test-textarea-value"></textarea>
<p class="test-html-pre"></p>
<p class="test-html-split"></p>
<p class="test-html-replace"></p>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top