How to insert line break in javascript

Asked

Viewed 29,727 times

2

My code has a Textarea, in it I send some messages, but when I jump a line, when receiving this message the line break is ignored

currently I use the following command in my javascript function to force line break

mensagem = document.getElementById("id_textarea_conteudo").value.replace("\n","<br>");

But it did not solve my problem, because instead of breaking all the jumped lines of the message, it is only breaking the first line.

example:

teste teste teste teste

is returning as follows

teste
teste teste teste

and I need you to return

teste 
teste
teste
teste

has some way to solve this problem I’m having?

1 answer

3


It’s up to \n even. <br> is for breaking lines in HTML, not input values.

const str = 'texto\ntexto\ntexto\ntexto'
document.getElementById('ta').value = str
const a = document.getElementById('ta').value.replace(/\\n/g, '<br>')
document.getElementById('dv').innerHTML = a
<textarea id="ta" style="height: 100px">
</textarea>

<div id="dv"></div>


Edit

If you want to recover the value of one textarea and use it in html, you have to replace using regular expression to replace all occurrences of \n, not only the first:

const texto = document.getElementById('minhaTextarea').value.replace(/\n/g, '<br>')
  • I ran a test this way and managed to make it work, what was missing was to correct the regular expression used instead of replace(" n","<br>") I changed to replace(/ r? n/g, '<br/>') and it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.