Sometimes, we want to preserve line breaks when getting text from a textarea with JavaScript.
In this article, we’ll look at how to preserve line breaks when getting text from a textarea with JavaScript.
How to preserve line breaks when getting text from a textarea with JavaScript?
To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>n'
.
For instance, we write
const post = document.createElement("p");
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/n/g, "<br>n");
to call replace
to replace all the n
characters with '<br>n'
.
Conclusion
To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>n'
.