How to add Line Breaks in a Textarea using JavaScript

Updated onbyAlan Morel
How to add Line Breaks in a Textarea using JavaScript

A textarea is an HTML element used when you want to input multi-line strings.

Because it is multi-line, it supports line breaks, which is how you can determine when to start the next line.

Thankfully, you can do this programmatically, giving you full control over where the new lines begin.

In this post, we'll learn how you can add line breaks in a textarea using JavaScript.

How to Add Line Breaks in a textarea using JavaScript

Let's first start with some example HTML markup:

HTML
<div> <textarea class="textarea"></textarea> </div>

Now let's query for the textarea element so that we can directly work with it.

We can do this using the document.querySelector() method:

JAVASCRIPT
const textarea = document.querySelector(".textarea");

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!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.