Add Line Breaks and Tabs in a String with JavaScript

01/19/2022
Contents
In this article, you will learn how to add line breaks and tabs in a string with JavaScript.
Add line breaks and tabs
Below is a sample with line breaks and tabs in the string.
//Line breaks
let str = 'Hello\nWorld!';
console.log(str);
//result
//"Hello
//World!"
//Tabs
let str = 'Hello\tWorld!';
console.log(str);
//result
"Hello World!"
Special characters are entered in the form of “\ + characters” in the parts that are replaced with line breaks and tabs at the time of output.
This is called an escape sequence, and it is a character string that represents a special character prepared in advance on the JavaScript side.
Escape sequences
Escape sequences are special strings that allow characters that cannot be represented by keyboard input to be represented in the form of “\ + characters”.
Below are the escape sequences available in JavaScript.
\b | Backspace |
---|---|
\t | Horizontal tab |
\v | Vertical tab |
\n | Line break |
\f | Form feed |
\r | Carriage Return |
\’ | Single quote |
\” | Double quote |
\` | Back quote |
\\ | Backslash |
\0 | Null |