Last updated: Mar 5, 2024
Reading time·2 min
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.
<!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.
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.
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:
console.log
the value of your textarea
.You can also use template literals to achieve the same result.
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.
You can learn more about the related topics by checking out the following tutorials: