Add Line Breaks and Tabs in a String with JavaScript

Web Dev
Sponsored links

In this article, I will introduce 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.

Sponsored links

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.

\bBackspace
\tHorizontal tab
\vVertical tab
\nLine break
\fForm feed
\rCarriage Return
\'Single quote
\"Double quote
\`Back quote
\\Backslash
\0Null