Before we add line breaks, let's first set the textarea's value to a sample string:
JAVASCRIPT
const textarea = document.querySelector(".textarea");
textarea.value = "This is a sample string";
That looks like this:
BASH
This is a sample string
As you can see, the string lives on a single line.
Now let's add line breaks to this.
To add a line break, you simply need to add \r\n to the string.
The \r is a carriage return which moves the character to the beginning of the line, and the \n is a line feed which moves the character to the next line.
Combined, these two characters create a line break by moving the cursor to the start of the next line.
Let's add this to our string:
JAVASCRIPT
const textarea = document.querySelector(".textarea");
textarea.value = "This is a sample string\r\nThis is the second line";
That looks like this:
BASH
This is a sample string
This is the second line
Keep in mind that you can also use template literals to add line breaks:
JAVASCRIPT
const textarea = document.querySelector(".textarea");
textarea.value = `This is a sample string
This is the second line`;
That looks like this:
BASH
This is a sample string
This is the second line
Conclusion
In this post, we learned how to add line breaks in a textarea using JavaScript.
Simply add \r\n to the string to add a line break and the browser will automatically render it for you.
Thanks for reading!
To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!