Add Line breaks to a Textarea using JavaScript

avatar

Borislav Hadzhiev

Wed Jan 05 20222 min read

banner

Photo by Thomas Kelley

Add Line breaks to a Textarea using JavaScript #

To add line breaks to a text area, use the addition (+) operator and add the string of \r\n at the place 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 new line 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 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

If you console.log the value of your text area, you'll see that line breaks are preserved.

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee