JavaScript

How to Use \n in a JavaScript String

The use of \n in JavaScript is much needed when dealing with long string values. More specifically, when designing a web page or a website where the placement of long paragraphs is required in the Document Object Model to manage the content. Also, in the case of allowing the programmers to search for line breaks in the text files. In such scenarios, using \n in JavaScript string can be helpful to maintain the proper format and enhance the overall document design.

This write-up will discuss the use of \n in a JavaScript string.

How to Use \n in a JavaScript String?

\n” can be used in a JavaScript string by simply placing it between the string value. In the other case, the same functionality can be applied using “template literals”.

Check out the following examples to have an idea about the stated concepts.

Example 1: Use \n in a JavaScript String by Placing it Between the String Value

In the following example, we will assign the string value in the variable named “string”. Here, “\n” will divide the added string into two halves:

let string = "This is JavaScript\nIt is a programming language"

 
Finally, log the resultant string value separated with a new line:

console.log(string);

 
The corresponding output will be as follows:


Alteratively, you can also apply the same functionality using “template literals

Example 2: Use Template Literals in a JavaScript String

Template Literals” use back-ticks (“) instead of (“”) to define a string and allows multi-line strings as well. This technique can be implemented by dividing the specific string value into multi lines in order to add a new line.

In the below-given example, we will store a string value in a variable named “string”. Also, divide the string value into multiple lines and log the corresponding string value on the console using template literals:

const string = `Linux Hint
This is a website`
console.log(string);

 
The output in this case will be as follows:


We have compiled the examples to use \n and template literals for adding a new line in a JavaScript string.

Conclusion

To use \n in JavaScript, place it between the string value to add the rest of the part to the next line. In the other case, you can also utilize the template literals to apply the same functionality using back-ticks and place the string value into multi-lines, which also outputs the same result. This manual discussed the usage of \n and the template literals in a JavaScript string.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.