Categories
JavaScript Answers

How to preserve line breaks when getting text from a textarea with JavaScript?

Spread the love

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'.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to preserve line breaks when getting text from a textarea with JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *