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!
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- How to deploy a Deno app using Docker
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Using Axios to Pull Data from a REST API