Skip to content
Advertisement

How can I make a JS string have newlines instead of showing n? [closed]

How can I make it so that a JavaScript string makes a new line instead of showing n? Say I have a string that goes: I Love JS!

but when I show it again it shows: InLovenJS!

How can I make it do a newline??

(for context, im making a sync notepad that syncs every second and it saves it to a db and the db turns it into a string and stores it, but when I get it back the newlines just turn into n’s)

Advertisement

Answer

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 = 'InLovenJS!';

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>');

console.log(str);
alert(str);
.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>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement