How to add Line breaks to a Textarea in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 5, 2024
2 min

banner

# Add Line breaks to a Textarea using JavaScript

To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break.

The combination of the \r and \n characters is used as a newline character.

Here is the HTML for the examples.

index.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <label for="message">Your message:</label> <textarea id="message" name="message" rows="5" cols="33" ></textarea> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const message = document.getElementById('message'); message.value = 'line one' + '\r\n' + 'line two' + '\r\n' + 'line three'; /** * line one * line two * line three */ console.log(message.value);
The code for this article is available on GitHub

If I open my browser, I can see that line breaks have been added at the places where I used the \r\n characters.

textarea line break

The \r character moves the cursor to the beginning of the line but doesn't move it to the next line.

The \n character moves the cursor down to the next line but doesn't return it to the beginning of the line.

The combination of the \r\n characters:

  • moves the cursor to the beginning of the line
  • advances the cursor down to the next line
You'll see that line breaks are preserved if you console.log the value of your textarea.

# Add Line breaks to a Textarea using template literals

You can also use template literals to achieve the same result.

index.js
const message = document.getElementById('message'); const first = 'line one'; const second = 'line two'; const third = 'line three'; message.value = `${first}\r\n${second}\r\n${third}`;

add line breaks to textarea using template literals

The code for this article is available on GitHub

We used template literals in the example.

The string is wrapped in backticks, not in single quotes.

The dollar sign curly braces syntax allows us to evaluate an expression directly in the template string.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.