How to add Line Breaks in a Textarea using JavaScript
Table of Contents
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:
JAVASCRIPTconst textarea = document.querySelector(".textarea");
Before we add line breaks, let's first set the textarea
's value to a sample string:
JAVASCRIPTconst textarea = document.querySelector(".textarea");
textarea.value = "This is a sample string";
That looks like this:
BASHThis 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:
JAVASCRIPTconst textarea = document.querySelector(".textarea");
textarea.value = "This is a sample string\r\nThis is the second line";
That looks like this:
BASHThis is a sample string
This is the second line
Keep in mind that you can also use template literals to add line breaks:
JAVASCRIPTconst textarea = document.querySelector(".textarea");
textarea.value = `This is a sample string
This is the second line`;
That looks like this:
BASHThis 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!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting User Location using JavaScript's Geolocation API
- Using Push.js to Display Web Browser Notifications