Add Line breaks to a Textarea using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

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, e.g. 'line one' + '\r\n' + 'line two'. The combination of the \r and \n characters is used as a newline character.

Here is the HTML for the examples in this article.

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>

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);

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.

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}`;

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.

Use the search field on my Home Page to filter through my more than 3,000 articles.